您的位置:首页 > 移动开发 > Android开发

Android ScrollView中嵌套GridView,ListView

2016-06-30 15:03 344 查看
最近开发中遇到一个问题,就是在ScrollView中嵌套GridView,ListView加载数据时,不管怎样都只显示一条数据。其它的数据都没出来。查询资料后来找到了完美的解决办法:

1:重写GridView,ListView

GridView的重写:

public class MyGridView extends GridView {
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyGridView(Context context) {
super(context);
}

public MyGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}


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


2:获得足够高度

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));
((MarginLayoutParams)params).setMargins(15, 15, 15, 15);
listView.setLayoutParams(params);

}


上面方法的使用:

ListView list = findViewById(R.id.listView);
setListViewHeightBasedOnChildren(list);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: