通常情況下我們不會在ScrollView中嵌套ListView,但是如果面試官非讓我嵌套的話也是可以的。
在ScrollView添加一個ListView會導致listview控件顯示不全,通常只會顯示一條,究竟是什么原因呢?
兩個控件的滾動事件沖突導致。所以需要通過listview中的item數量去計算listview的顯示高度,從而使其完整展示,如下提供一個方法供大家參考。
解決辦法如下所示:
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); }現階段最好的處理的方式是: 自定義ListView,重載onMeasure()方法,設置全部顯示。
import android.widget.ListView; /** * * @Description: scrollview 中內嵌 listview 的簡單實現 * * @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,如果不設置,系統默認設置是顯示兩條 */ public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }以上內容是小編給大家介紹的ScrollView中嵌入ListView只顯示一條的解決辦法,希望對大家有所幫助!
新聞熱點
疑難解答