通常情況下我們不會(huì)在ScrollView中嵌套ListView,但是如果面試官非讓我嵌套的話也是可以的。
在ScrollView添加一個(gè)ListView會(huì)導(dǎo)致listview控件顯示不全,通常只會(huì)顯示一條,究竟是什么原因呢?
兩個(gè)控件的滾動(dòng)事件沖突導(dǎo)致。所以需要通過listview中的item數(shù)量去計(jì)算listview的顯示高度,從而使其完整展示,如下提供一個(gè)方法供大家參考。
解決辦法如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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); } |
現(xiàn)階段最好的處理的方式是: 自定義ListView,重載onMeasure()方法,設(shè)置全部顯示。
1
2
3
4
5
6
7
8
9
10
11
12
|
import android.widget.ListView; /** * * @Description: scrollview 中內(nèi)嵌 listview 的簡單實(shí)現(xiàn) * * @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,如果不設(shè)置,系統(tǒng)默認(rèn)設(shè)置是顯示兩條 */ public void onMeasure( int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2 , MeasureSpec.AT_MOST); super .onMeasure(widthMeasureSpec, expandSpec); } } |
以上內(nèi)容是小編給大家介紹的ScrollView中嵌入ListView只顯示一條的解決辦法,希望對(duì)大家有所幫助!