zoukankan      html  css  js  c++  java
  • 项目中那些事|ListView中嵌套ListView问题


    要在一个ListView中放入另一个ListView,也即在一个ListView的每个 item 中放入另外一个ListView。但刚开始的时候,会发现放入的子ListView会显示不完全(我这里只显示前一项),它的高度始终有问题。因为默认情况下Android是禁止在ScrollView中放入另外的ScrollView的,这种设计是不推荐的。

    但是项目需要,发现有StackOverflow(这里给大家推荐一下 http://stackoverflow.com/questions/tagged/android ,一个不错的问答网站)上的牛人已经解决了这个问题,经过试验发现是可以解决问题的,它的思路就是在设置完ListView的Adapter后,根据ListView的子项目重新计算ListView的高度,然后把高度再作为LayoutParams设置给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);    
        } 


    在设置ListView的Adapter后调用此静态方法即可让ListView正确的显示在其父ListView的 itme 中。但是要注意的是,子ListView的每个Item必须是LinearLayout,不能是其他的,因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常。







  • 相关阅读:
    .NET总结
    gzip压缩输出
    矩阵 快速幂
    Mock单元测试
    mysql乱码原因之一
    写个android下倒计时软件
    linux gcc下实现简单socket套接字小程序
    gcc下MD5破解
    #1045 Access denied for user 'root'@'localhost'
    转android四种动画
  • 原文地址:https://www.cnblogs.com/riskyer/p/3285641.html
Copyright © 2011-2022 走看看