ListView 在ListView中嵌套 以及ListView 在ScrollView 中显示的时候。经常会出现 listView 只显示一行的情况,或者显示高度异常,焦点获取不到的方法,重写一下ListView即可。 同理 如果是 gridView 也这样做。
方法1:
下面是通用方法:
public class List extends ListView{
public List(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
/**
* Integer.MAX_VALUE >> 2,如果不设置,系统默认设置是显示两条
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
方法2 :适用listView ,大多数网上介绍的方法,基本可用,但是特殊情况会不管用:
这个方法调用放在 listView刷新之后
/**
* 获取listview高度
*
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = (ListAdapter) listView.getAdapter();
if(listAdapter ==null) {
return;
}
int inttotalHeight =0;
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(0,0,0,0); //设置maring . listView.setLayoutParams(params);
}