美文网首页Android开发常用代码程序员
ScrollView嵌套ListView冲突解决方案

ScrollView嵌套ListView冲突解决方案

作者: 才兄说 | 来源:发表于2017-06-08 10:04 被阅读31次

    方案一:动态计算ListView的item总高度

    动态设置ListView的高度 ,该方法必须在listview设置了adapter之后调用

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if(listView == null)
            return;
    
        ListAdapter listAdapter = (ListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
    
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(50, 50);//置空,注意:这里的listview的子项的最大布局必须是LinearLayout布局
            totalHeight += listItem.getMeasuredHeight(); //循环得到listview的所有item高度的总和  
        }
    
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
    

    方案二:重写ListView的onMeasure()方法

    public class ExpandListView extends ListView {
       public ExpandListView(Context context) {
          super(context);
       }
       
       public ExpandListView(Context context, AttributeSet attrs) {
          super(context, attrs);
       }
    
       @Override
       public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
          int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
          super.onMeasure(widthMeasureSpec, expandSpec);
       }
    }
    

    相关文章

      网友评论

        本文标题:ScrollView嵌套ListView冲突解决方案

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