How can i have a ListView inside a NestedScrollView

后端 未结 4 1679
盖世英雄少女心
盖世英雄少女心 2021-01-05 07:52

I have created an app with a page that need to load content dynamically from web service. I want to have listview that can scroll together with a linear layout inside Nested

4条回答
  •  一个人的身影
    2021-01-05 08:21

    Just use this code, if you want to make listview expand in a nestedscrollview. Pass the listview reference to the function at the end of creating listview.

    private static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null)
            return;
    
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, view, listView);
            if (i == 0)
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
    
            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
    

提交回复
热议问题