Android动态获取ListView的高度

今天介绍一下怎么动态的获取listview的高度。看代码:

public static void getTotalHeightofListView(ListViewlistView){
   
ListAdapter mAdapter = listView.getAdapter();
 
    if (mAdapter== null) {
       return;
    }
   
int totalHeight = 0;
   
for (inti = 0;i <</SPAN> mAdapter.getCount();i++){
       
View mView = mAdapter.getView(i,null,listView);
       mView
.measure(
               
MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED),
               
MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED));

        //mView.measure(0,0);

       totalHeight += mView.getMeasuredHeight();
       
Log.w("HEIGHT"+ i,String.valueOf(totalHeight));
   
}
   
ViewGroup.LayoutParamsparams = listView.getLayoutParams();
   
params.height= totalHeight
           
+ (listView.getDividerHeight()* (mAdapter.getCount()- 1));

   listView
.setLayoutParams(params);
   listView
.requestLayout();
   }

使用这个代码来获取listview的高度,需要注意一下几个问题:

1、listview的item的根布局一定要是LinearLayout;

2、调用这个方法需要在适配器数据加载更新之后;代码如下:

mAdapter.notifyDataSetChanged();
   Function.getTotalHeightofListView(mListView);

3、获取item的高度也可以用注释掉的代码,效果一样的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值