我希望在收到网址回复时显示包含部分内容的ListView
。
要从底部显示ListView
我所做的是,我已将其放在LinearLayout(它的父级)的末尾,visibility
设置为gone
。
布局文件:
</LinearLayout>
.
.
.
<!-- ListView at bottom -->
<ListView
android:id="@+id/places_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray"
android:visibility="gone" >
</ListView>
</LinearLayout>
当我想显示ListView
时,我会将其显示并使用动画进行翻译,如下所示:
// Show listView that displays a list of items
private void showListView() {
ObjectAnimator animator = null;
placeListView.setVisibility(View.VISIBLE);
// Display listView with animation
if (activeEditTextId == R.id.from_location) {
animator = ObjectAnimator.ofFloat(placeListView, "y", fromLocation.getY() + fromLocation.getHeight() + 5);
} else if (activeEditTextId == R.id.to_location) {
animator = ObjectAnimator.ofFloat(placeListView, "y", toLocation.getY() + toLocation.getHeight() + 5);
}
animator.setDuration(2000);
animator.start();
listAdapter.notifyDataSetChanged();
}
但问题是,使用此布局,ListView
高度仅为37。我理解这是因为ListView
的最后只有那么高的高度。
但是如何显示ListView
全尺寸,即所有项目一次可见?
答案 0 :(得分:4)
我通过在列表内容更改时以及在显示ListView
之前动态计算ListView
的高度来解决我的问题。
从this link复制代码。
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.requestLayout();
}