Android: Listview inside ScrollView

后端 未结 4 1890
抹茶落季
抹茶落季 2021-01-23 17:35

I want to have a layout that can scroll and a listview inside it. The listview will expand it\'s height base on how many items in it. Only the ScrollView outside is scrollable.

相关标签:
4条回答
  • 2021-01-23 18:12

    Actually, it is possible to put a ListView inside of an ScrollView. In some use cases (e.g. dynamic menus/submenus it's a reasonable solution). However, two caveats apply:

    • The ListView won't have scroll. In general, nested scrolling is not possible in Android. There are some hacks to make it work (mostly by using requestDisallowInterceptTouchEvent()) but it's hard to make them work correctly in all cases.
    • As a consequence, you must indicate the exact height the ListView needs to show all items (via its appropriate LayoutParams). Setting WRAP_CONTENT will not work.
    0 讨论(0)
  • 2021-01-23 18:28

    You have to just replace your <ScrollView ></ScrollView> with this Custom ScrollView like <com.tmd.utils.VerticalScrollview > </com.tmd.utils.VerticalScrollview >

    try this link...https://stackoverflow.com/a/11554684/6334037

    Works for me..

    0 讨论(0)
  • 2021-01-23 18:37

    Don't put ListView inside ScrollView - first rule of android clud :) Instead you can use simple LinearLayout and manage you ListView items inside it. Or you can add Header/Footer Views to the ListView and using it without scrollview.

    0 讨论(0)
  • 2021-01-23 18:37

    I used below lines of code to scroll list item inside scroll view. It's working fine for my requirement, i hope it will help you.

    Thanks, Murali.M

    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();
        }
    
    0 讨论(0)
提交回复
热议问题