Android中scrollview嵌套webview的实现

xiaoxiao2021-02-28  143

Android中,默认情况下,scrollview中如果再嵌套一个webview,会出现webview无法展示的以及这个scrollview无法滑动的问题,因为scrollview需要根据内部的内容计算高度,webview也需要更具内部的内容计算高度,而且他们都是可以滑动的,就存在滑动的冲突,然而,现实情况下,总是就会存在这样的需求,需要去这样子去嵌套来完成需求。怎么办?当然是,解决冲突,嵌套使用,实现需求呀。

其实实现起来,也是相当的简单,这和scrollview嵌套listview是完全类似的原因和操作,包括现象都一样啊,那么就撸代码:

/** * @author jakezhang * @date 2016年4月26日 */ public class NoScrollWebView extends WebView { @SuppressLint("NewApi") public NoScrollWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public NoScrollWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public NoScrollWebView(Context context, AttributeSet attrs) { super(context, attrs); } public NoScrollWebView(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, mExpandSpec); } }

xml中:

<ScrollView android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.freedev.tool.view.NoScrollWebView android:id="@+id/webViewNet" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" /> </LinearLayout> </ScrollView>

在activity中:

webView.loadData(url, "text/html; charset=UTF-8", "UTF-8");

这样一来,就可以了,scrollview中可以嵌套webview,也可以加入其它的东西一起在这个scrollview中滑动了。

转载请注明原文地址: https://www.6miu.com/read-36341.html

最新回复(0)