1

我想在ListView收到 URL 响应时显示一些项目。

为了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全尺寸显示,即所有项目一次可见?

4

1 回答 1

4

ListView我通过在列表内容更改时和显示之前动态计算高度来解决我的问题ListView从此链接
复制代码。

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();
}
于 2013-06-26T09:45:17.607 回答