【Android】Item高度固定下动态设置ListView的高度

本文详细介绍了如何在Android应用中优化ListView布局,包括使用自定义函数将DP转换为像素,以及动态调整ListView高度以适应不同设备的屏幕大小。通过实例演示了如何实现这些功能,确保应用在各种设备上都能提供良好的用户体验。
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="44dp"
    android:paddingLeft="10dp"
    android:background="@color/white"
    android:descendantFocusability="blocksDescendants"
    android:paddingBottom="1dp">
    
   android:id="@+id/tv_contact_name"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerVertical="true"
   android:layout_toRightOf="@+id/iv_contact_photo"
   android:textColor="@color/black" />
   android:id="@+id/iv_contact_photo"
   android:layout_width="40dp"
   android:layout_height="40dp"
   android:layout_alignParentLeft="true"
   android:layout_centerVertical="true"
   android:layout_margin="5dp" />
       


在使用此listView的布局中设置属性
<ListView
    android:id="@+id/lv_addEventContact"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbarSize="0dp"
    android:dividerHeight="0dp"
    android:visibility="gone"
    />

定义一个函数将dp转换为像素
public int Dp2Px(Context context, float dp) { 
    final float scale = context.getResources().getDisplayMetrics().density; 
    return (int) (dp * scale + 0.5f); 
}


定义函数动态控制listView的高度
public void setListViewHeightBasedOnChildren(ListView listView) {

    //获取listview的适配器
    ListAdapter listAdapter = listView.getAdapter();
    //item的高度
    int itemHeight = 46;

    if (listAdapter == null) {
        return;
    }

    int totalHeight = 0;

    for (int i = 0; i < listAdapter.getCount(); i++) {
    totalHeight += Dp2Px(getApplicationContext(),itemHeight)+listView.getDividerHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight;

    listView.setLayoutParams(params);
}


在每次listView的adapter发生变化后,要调用setListViewHeightBasedOnChildren(listView)更新界面

转:http://blog.sina.com.cn/s/blog_4b20ae2e0101abvg.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值