由于WebView 和 ScrollView都是可以滚动的,当这两个View嵌套时,容易出现一些问题。其中比较常见的,是嵌套在 ScrollView 中的WebView 的焦点问题.
方案1: (有问题的)
【通过手动调用 mScrollView.smoothScrollTo(0, 0),使SrcollView强制滚回最前端】
当处理这个问题的时候,首先想到的是,到底哪里做了SrcollView的滚动,结果通过断点找了半天没有找到。所以使用了上述方法,强制使SrcollView滚动回最前端。
遇到问题:
由于Webview加载URL时是异步的,所以当URL中内容比较多时,偶尔还是会遇到自动滚动到WebView处。
方案2:(解决问题)
【通过给WebView所属的ViewGroup设置 android:descendantFocusability="blocksDescendants"】
如果不做任何处理,则会出现WebView加载后获得焦点,在WebView并非占满屏幕时点击WebView内容,ScrollView就会自动滚动,使WebView占满屏幕。
经过一番搜索研究,发现解决方法竟出奇的简单,只需要一行:
1 <ScrollView 2 android:id="@+id/sv" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent"> 5 6 7 <!--增加descendantFocusability,处理由于webview加载获取到焦点,使scrollView自动滚动--> 8 <LinearLayout 9 android:layout_width="match_parent" 10 android:layout_height="match_parent" 11 android:descendantFocusability="blocksDescendants" 12 android:orientation="vertical"> 13 14 …………………… 15 …………………… 16 17 <WebView 18 android:id="@+id/mWebView" 19 android:layout_width="match_parent" 20 android:layout_height="wrap_content" /> 21 </LinearLayout> 22 </ScrollView>
descendantFocusability属性的作用是当一个view获取焦点时,定义viewGroup和其子控件两者之间的关系。而blocksDescendants是viewgroup会覆盖子类控件而直接获得焦点。