我在设置ListView的高度方面遇到了一些问题
我的ListView
位于ScrollView
内,并且填充了一些元素。为了让ListView
展开,我会以编程方式计算元素的高度,并相应地设置ListView
高度。
由于某些原因,我的措施不正确
这是我的ListView
项目布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_media_play"
android:tint="@android:color/black"
android:background="@android:color/transparent"
android:padding="12dp"
/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_trailer_item_title"
android:textSize="22dp"
android:textColor="#000000"
android:textStyle="italic"
android:padding="12dp"
/>
</LinearLayout>
这是我设置ListView
身高的代码:
public void setListViewHeightBasedOnChildren(ListView listView) {
TrailersAdapter listAdapter = (TrailersAdapter) listView.getAdapter();
if (listAdapter == null) {
return;
}
int elements = listAdapter.getCount();
Log.d("AAA","Got " + elements + " elements");
if (elements>0) {
View listItem = listAdapter.getView(0, null, listView);
listItem.measure(0,0);
//get the height of a single item, multiply by the number of items and get the total height for the items
int totalHeight = listItem.getMeasuredHeight() * elements;
ViewGroup.LayoutParams params = listView.getLayoutParams();
//calculate the total height summing the height of the dividers too
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount()-1));
//set the height
listView.setLayoutParams(params);
}
}