ScrollView中嵌套WebView时可能会出现焦点问题

  我们都知道,WebView 和 ScrollView都是可以滚动的,当这两个View嵌套时,容易出现一些问题。其中比较常见的,是嵌套在 ScrollView 中的WebView 的焦点问题.

  例如这个结构:

 

 1   <ScrollView
 2      android:id="@+id/sv"
 3      android:layout_width="fill_parent"
 4      android:layout_height="fill_parent">
 5      <LinearLayout
 6          android:layout_width="fill_parent"
 7          android:layout_height="wrap_content"
 8          android:orientation="vertical">
 9          <TextView
10              android:layout_width="fill_parent"
11              android:layout_height="wrap_content"
12              android:text="top" />
13          <WebView
14              android:id="@+id/lv"
15              android:layout_width="fill_parent"
16              android:layout_height="wrap_content">
17          </WebView>
18          <TextView
19              android:layout_width="fill_parent"
20              android:layout_height="wrap_content"
21              android:text="bottom" />
22      </LinearLayout>
23   </ScrollView>

 

 

 

  如果不做任何处理,则会出现WebView加载后获得焦点,在WebView并非占满屏幕时点击WebView内容,ScrollView就会自动滚动,使WebView占满屏幕。(ListView也会出现类似问题,即使修正了高度,也会主动获得焦点,使得屏幕产生错误的滚动)。经过一番搜索研究,发现解决方法竟出奇的简单,只需要一行:

      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:descendantFocusability="blocksDescendants">  

 

  descendantFocusability属性的作用是当一个view获取焦点时,定义viewGroup和其子控件两者之间的关系。而blocksDescendantsviewgroup会覆盖子类控件而直接获得焦点。

 

参考:

http://stackoverflow.com/questions/9842494/how-to-prevent-a-scrollview-from-scrolling-to-a-webview-after-data-is-loaded

http://www.cnblogs.com/eyu8874521/archive/2012/10/17/2727882.html

 

posted @ 2015-11-18 17:31  NoodleUtopia  阅读(7112)  评论(1编辑  收藏  举报