Android:如何在列表视图中显示前三项并在滚动中休息

时间:2013-08-21 08:11:56

标签: android listview

enter image description here目前我正在使用可见性“GONE”显示listview,然后在按钮点击时显示“VISIBLE”,但它在listview中只显示1项,在scrollview中显示其他元素(我需要滚动),所以我决定保持listview首先显示至少3个项目,并在listview滚动上显示rest元素。 如何解决这个问题,提前谢谢。

第一张图片是我的代码 我需要有第二张图片

1 个答案:

答案 0 :(得分:4)

一般来说,ScrollView中的ListView是一个坏主意。

相反,你应该使用LinearLayout并在那里膨胀你的ListItems。 不太难做。只需使用for循环或其他东西。 如果您必须使用ListView,则可以在填充ListView之后在ListView上调用以下方法。

(将listAdapter.getCount()更改为您要显示的单元格数

 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);
    }