问题: 为什么scrollView中的listView/gridView只显示一行?
原因:由于listView/gridView在scrollView中无法正确计算它的大小, 故只显示一行.
最佳解决方案:
重写ListView, 覆盖onMeasure()方法:设置让listView能有多高就多高.
public class WrapListView extends ListView{
public WrapListView(Context context) {
super(context);
}
public WrapListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WrapListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
gridView与listView相同:
public class WrapGridView extends GridView{
public WrapGridView(Context context) {
super(context);
}
public WrapGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WrapGridView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
不重写ListView的方案
private void setListViewHeight(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));
listView.setLayoutParams(params);
}
建议使用最佳方案, 只需在布局文件中将对应的listView标签替换即可
希望对大家的学习有所帮助~~~