今天在優(yōu)化項(xiàng)目的時(shí)候發(fā)現(xiàn)需要用到ScrollView同時(shí)嵌套ListView和GridView ,普通的寫(xiě)上去發(fā)現(xiàn) ListView和GridView 都無(wú)法正常顯示 (只顯示一行) ,這很憂傷啊 .
在網(wǎng)上找了點(diǎn)資料 ,問(wèn)題解決了 ,在此記錄下來(lái) :
/**
* 自定義GridView 用于ScrollView 嵌套的問(wèn)題
* 重寫(xiě)GridView,讓其失去滑動(dòng)特性:(重寫(xiě)ListView也是和GridView重寫(xiě)的方法一 樣)
*/
public class MyGridView extends GridView {
public MyGridView (Context context, AttributeSet attrs){
super(context, attrs);
}
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, mExpandSpec);
}
}
對(duì)于ListView 我沒(méi)用上面的方法 ,我只設(shè)置ListView的高度 寫(xiě)的一個(gè)工具類
/**
* 設(shè)置ListView高度
*/
public class ListViewUtil {
public static void setListViewHeight(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
// 返回?cái)?shù)據(jù)項(xiàng)的數(shù)目
View listItem = listAdapter.getView(i, null, listView);
// 計(jì)算子項(xiàng)的高度
listItem.measure(0, 0);
// 統(tǒng)計(jì)所有子項(xiàng)的高度
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
注意 : 要在
mList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged(); // 后調(diào)用
ListViewUtil.setListViewHeight(mList);