Normally, we won't nest ListView in ScrollView, but it's OK if the interviewer insists that I nest.
Adding a ListView to a ScrollView will cause the listview control to be incomplete, and usually only one will be displayed. What is the reason?
The scroll event conflict between the two controls results in . Therefore, it is necessary to calculate the display height of the listview through the number of items in the listview to make it fully displayed. The following method is provided for your reference.
The solution is as follows:
lv = (ListView) findViewById(R.id.lv); adapter = new MyAdapter(); lv.setAdapter(adapter); setListViewHeightBasedOnChildren(lv); --------------------------------------------------- public void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { 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)); params.height += 5; listView.setLayoutParams(params); }The best way to deal with it at this stage is: custom ListView, overload the onMeasure() method, and set all displays.
import android.widget.ListView; /** * * @Description: A simple implementation of embedded listview in scrollview* * @File: ScrollViewWithListView.java * * * @Version */ public class ScrollViewWithListView extends ListView { public ScrollViewWithListView(android.content.Context context, android.util.AttributeSet attrs) { super(context, attrs); } /** * Integer.MAX_VALUE >> 2. If not set, the system default setting is to display two pieces */ public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }The above content is the solution to embed ListView in ScrollView that the editor introduced to you. I hope it will be helpful to everyone!