Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ScrollView 嵌套 ListView 顯示不全的解決方案

編輯:關於 Android 程式設計

一般情況下,我們不會在 ScrollView 中嵌套 ListView,但若真有這種需求,也并非無法實現。在 ScrollView 中加入 ListView,會導致 ListView 顯示不全,通常只顯示一條,這是因為兩個控件的滾動事件相互衝突所致。因此,需要根據 ListView 中 item 的數量來計算其顯示高度,讓它能完整呈現。以下提供一個方法供參考。

 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); } }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved