Android之ScrollView嵌套ListView顯示不全的問題

【網上很多說使用動態修改listview高度的方法,然而並不能解決每個item高度不同的listview的顯示不全的問題。如下第一種方法,建議使用第二種方法】

一、在數據適配器通知數據改變後調用以下方法,動態修改listview的高度

[代碼]:
===================
/**
  * 動態設置ListView的高度
  * @param listView
  */
 public static void setListViewHeightBasedOnChildren(ListView listView) {
     if(listView == null) return;

     ListAdapter listAdapter = listView.getAdapter();
     if (listAdapter == null) {
         // pre-condition
         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));
     listView.setLayoutParams(params);
 }
===================

二、那麼我們來介紹這個更強大的辦法,重寫ListView

代碼:
===================
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

public class MyListView extends ListView {  
	  
    public MyListView(Context context) {  
        // TODO Auto-generated method stub  
        super(context);  
    }  
  
    public MyListView(Context context, AttributeSet attrs) {  
        // TODO Auto-generated method stub  
        super(context, attrs);  
    }  
  
    public MyListView(Context context, AttributeSet attrs, int defStyle) {  
        // TODO Auto-generated method stub  
        super(context, attrs, defStyle);  
    }  
  
    @Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        // TODO Auto-generated method stub  
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,  
                MeasureSpec.AT_MOST);  
        super.onMeasure(widthMeasureSpec, expandSpec);  
    }  
}  

====================
接下來只要在佈局使用就可以了
代碼:
====================
<com.test.view.MyListView
    android:id="@+id/lvComments"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="@dimen/dimen_20_dip"
    android:divider="@null"
    android:scrollbars="@null" >
</com.test.view.MyListView>
====================


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章