自定义弹框时,弹框中需要webView加载内容,如果webView内容很长,弹框会撑满页面,现在不想让弹框撑满,而是可以自己限制弹框最高高度,内容长度没有达到最高高度时,弹框高度根据内容自适应,内容长度超过最高高度时,弹框高度限制在最高高度,这样就不能直接写死弹框高度,而是要动态设置了。
第一个想到方法是在webView加载完内容后获取webView高度,然后去设置弹框高度:
val webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
// 获取webView高度,再设置dialog高度
webView?.measure(0, 0)
val height = webView?.measuredHeight ?: 0
if (height > Resources.getSystem().displayMetrics.heightPixels * 4 / 5) {
window?.attributes?.height = Resources.getSystem().displayMetrics.heightPixels * 4 / 5
}
}
}
实验发现无效,webview内容超过4/5屏幕高度,弹框依然会撑满屏幕。
有效方法:
自定义webView,在高度上做设置:
class MaxHeightWebView: WebView {
private var mMaxHeight = -1
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, privateBrowsing: Boolean) : super(context, attrs, defStyleAttr, privateBrowsing)
fun setMaxHeight(height: Int) {
mMaxHeight = height
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (mMaxHeight >- 1 && measuredHeight > mMaxHeight){
setMeasuredDimension(measuredWidth, mMaxHeight)
}
}
}
dialog的布局文件中使用:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/shape_white_top_corner_r10"
android:paddingLeft="15dp"
android:paddingTop="25dp"
android:paddingRight="15dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:overScrollMode="never"
android:orientation="vertical">
<TextView
android:id="@+id/titleTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_gravity="center_horizontal"
android:text="重要提示"
android:textSize="18sp"
android:textColor="#DE000000"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<com.view.MaxHeightWebView
android:id="@+id/contentWV"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<TextView
android:id="@+id/confirmTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dpg"
android:background="@drawable/shape_corner_5_solid_primary"
android:padding="10dp"
android:gravity="center"
android:text="我知道了"
android:textSize="18sp"
android:textColor="@android:color/white"/>
</LinearLayout>
dialog在OnCreate时候,设置下webView的最大高度
webView?.setMaxHeight(PixValue.m.heightPixels * 3 / 5)
运行代码,达到我们想要的效果。