Android ListView和GridView去掉滾動效果

          做過的項目裏面認爲列表使用的最多了,用時候需要ListView嵌套ListView或是ListView嵌套GridView,或是ScrollView嵌套ListView或是GridView ,發現滾動嵌套滾動會有佈局顯示不完全等問題,現在就解決這個問題

        原來解決ScrollView嵌套ListView時會用一個方法重新計算ListView的Item高度累加起來:

public static void setListViewHeight(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();// 獲取ListView對應的Adapter
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回數據項的數目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 計算子項View 的寬高
			totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}
       這個方法需要在setAdapter()之後設置,ListView的每個Item必須是LinearLayout,不能是其他的,因爲其他的Layout(如RelativeLayout)沒有重寫onMeasure(),所以會在onMeasure()時拋出異常。但是這種方式會計算兩次Item的高度。下面再給出一種方法,這是重寫ListView或是GridView的onMeasure()方法,具體方法如下:

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);
		}



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