ScrollView中嵌入ListView只顯示一條的處理方法。本站提示廣大學習愛好者:(ScrollView中嵌入ListView只顯示一條的處理方法)文章只能為提供參考,不一定能成為您想要的結果。以下是ScrollView中嵌入ListView只顯示一條的處理方法正文
平日情形下我們不會在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只顯示一條的處理方法,願望對年夜家有所贊助!