ListView contents get cutoff after Adapter update

前端 未结 3 1678
半阙折子戏
半阙折子戏 2021-01-25 01:02

I have a number of vertically stacked panels in my UI. Each panel contains a ListView. Based on user interaction, the number of items in the ListView gets updated.

My pr

相关标签:
3条回答
  • 2021-01-25 01:45

    try this function. I think, it might help you. The function is used to set ListView's height based on its children.

    public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                // pre-condition
                return;
            }
    
            int totalHeight = 0;
            int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
                totalHeight += listItem.getMeasuredHeight();
            }
    
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
            listView.requestLayout();
        }
    
    0 讨论(0)
  • 2021-01-25 01:45

    If your listview is a default size, it might not be able to fit them in the layout. You could try to wrap the listview in a scrollview and then you can scroll through them.

    0 讨论(0)
  • 2021-01-25 01:50

    (You can add a ListView inside a ScrollView but not without a little work (as they are both Scrollable components - how would the OS know which one you're trying to scroll?). You would need to add isScrollContainer="false" on your ListView.)

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_contents"
        android:isScrollContainer="false"/>
    

    The entire point of a ListView is it has a set height as dictated by the layout of your page. It only becomes scrollable when it's children's combined height exceed the area required to display it.

    It sounds like what you actually want is something more akin to a LinearLayout which is backed by an Adapter, there are several implementations out there on the web or you can create your own.

    However, you can hack a ListView into this behaviour by dynamically resizing your ListView programatically by setting it's Height to: listCount * itemHeight. This would have the effect of consistently expanding your ListView.

    You will likely find that as you develop your UI design you will no longer require such a component.

    0 讨论(0)
提交回复
热议问题