美文网首页
ScrollView 和 ListView 的冲突解决

ScrollView 和 ListView 的冲突解决

作者: 清枫浦上 | 来源:发表于2017-01-09 16:46 被阅读0次

ScrollView与ListView都具有滚动能力,对于这样的View控件,当ScrollView与ListView相互嵌套时会出现一些问题:
问题一:ScrollView与ListView嵌套导致ListView显示不全面
问题二:ScrollView不能正常滑动

1)动态设置listview高度

/** 动态设置listview高度
 * @param listView
 */
public void setListViewHeight(ListView listView) {
     ListAdapter adapter = listView.getAdapter();
     if (adapter == null) {               
        return;           
     }

     int totalHeight = 0;
     for (int i = 0; i < adapter.getCount(); i++) {
         View listItem = adapter.getView(i, null, listView);
         listItem.measure(0, 0);
         totalHeight += listItem.getMeasuredHeight();
     }

     ViewGroup.LayoutParams params = listView.getLayoutParams();
     params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1)) + 15;
     listView.setLayoutParams(params);
}

这种方案的解决方法,缺点是convertView 为null


2)ListView 和 ScrollView 冲突的另一种解决方案(重写ListView)

/* 
 * @see android.widget.ListView#onMeasure(int, int)
 * 重写该方法,以适应scrollview
 */
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
     int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
 MeasureSpec.AT_MOST);
     super.onMeasure(widthMeasureSpec, expandSpec);
}

存在问题:进入页面的时候,是从ListView 开始的,ScrollView 上面没有显示,要下拉的时候才显示。
解决方案:在ScrollView 的孩子根布局加上:

android:focusable="true" 
android:focusableInTouchMode="true"

3)最后建议尽量不要ScrollView套AdapterView,虽然有方案解决,但是会影响性能,尽量使用ListView添加头部,尾部和多布局来实现相同的效果。

相关文章

网友评论

      本文标题:ScrollView 和 ListView 的冲突解决

      本文链接:https://www.haomeiwen.com/subject/tzdhbttx.html