ListView 内嵌套ListView,子ListView内的高度无法正常显示

       最近在做一个类似于微信朋友圈的项目,在主布局ListView里嵌套了子ListView,而子ListView 是动态显示好友的评论,预想中的效果是显示出全部评论,但是显示的只是最新的那条评论,其它的评论显示不了。

分析项目达不到效果原因,是因为无法动态的计算出子ListView 在父布局里占用的高度。


因此我们需要动态计算出子listView 每个Item的高度之和,然后设置到父布局


(1)计算子listView 里item 占据的高度之和

  public void setListViewHeightBasedOnChildren(ListView listView) {
        
ItemsReplyAdapter listAdapter = (ItemsReplyAdapter) listView.getAdapter();
if (listAdapter == null) {
return;
}

int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; 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));
params.height = totalHeight;
// listView.getDividerHeight()获取子项间分隔符占用的高度
// params.height最后得到整个ListView完整显示需要的高度
listView.setLayoutParams(params);
}


(2) 将这个高度设置到父布局

  在父布局所对应的adapter 中的 getView 方法调用此方法

      setListViewHeightBasedOnChildren(holder.replyList);


至此ListView 可以显示出全部评论,解决了以上的问题


*****   但是在这个项目中,子listView 里用了textView 来显示评论,如果评论的行数,不知有一行,又会出现最先评论的不会显示,那就说明计算子listView的高度还是不准确。

(3)解决由textView 多行带来的问题

应该重写一个TextView的onMeasure方法

@Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  
        Layout layout = getLayout();  
        if (layout != null) {  
            int height = (int)FloatMath.ceil(getMaxLineHeight(this.getText().toString()))  
                    + getCompoundPaddingTop() + getCompoundPaddingBottom();  
            int width = getMeasuredWidth();              
            setMeasuredDimension(width, height);  
        }  
    }  
  
    private float getMaxLineHeight(String str) {  
        float height = 0.0f;  
        float screenW = ((Activity)context).getWindowManager().getDefaultDisplay().getWidth();  
        float paddingLeft = ((LinearLayout)this.getParent()).getPaddingLeft();  
        float paddingReft = ((LinearLayout)this.getParent()).getPaddingRight();  


//这里具体this.getPaint()要注意使用,要看你的TextView在什么位置,这个是拿TextView父控件的Padding的,为了更准确的算出换行  
 int line = (int) Math.ceil( (this.getPaint().measureText(str)/(screenW-paddingLeft-paddingReft))); height = (this.getPaint().getFontMetrics().descent-this.getPaint().getFontMetrics().ascent)*line; return height;}  

在ListView开始测量时,测量到TextView时,就调用onMeasure方法,我们就可以测量字体的总宽度除与去掉边距的屏幕的大小,就可以算出文字要几行来显示,然后测量字体的高度*行数可以得到字体的总高度,然后在加上上下边距就是TextView真正的高度,然后setMeasuredDimension进去就可以计算出正确的值出来。


参考博客:http://www.cnblogs.com/zmc/p/4013053.html



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值