ScrollView和ListView一起使用会有冲突,ListView显示不全。 如何解决网上也有很多例子,这里只说两种简单的方案。

1. 手动计算ListView高度,方法如下:

public static void setListViewHeightBasedOnChildren(ListView listView) {  
        ListAdapter listAdapter = listView.getAdapter();   
        if (listAdapter == null) {  
            // pre-condition  
            return;  
        }  
  
        int totalHeight = 0;  
        for (int i = 0; i < listAdapter.getCount(); i++) {  
            View listItem = listAdapter.getView(i, null, listView);  
            listItem.measure(0, 0);  
            totalHeight += listItem.getMeasuredHeight();  
        }  
  
        ViewGroup.LayoutParams params = listView.getLayoutParams();  
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
        listView.setLayoutParams(params);  
    }  

这里使用measuredHeight获取高度,measuredHeight并不是实际高度,因此该方法计算出的高度与实际的高度会有误差。

 

2. 重写ListView的onMeasure方法,重新计算每个子Item的高度

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //根据模式计算每个child的高度和宽度
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

 

相关文章:

  • 2022-12-23
  • 2021-08-14
  • 2021-09-26
  • 2021-05-18
  • 2021-06-12
  • 2021-07-29
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-05
  • 2021-10-09
  • 2021-07-07
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案