1:ScrollView和ListView的?
有时候项目里面需要ScrollView嵌套ListView,但是正常下ListView只会显示一行多一点,解决方法就是填充ListView数据后
重新计算ListView的高度,这里有两种方法来实现。
***(1)第一种方法:重写ListView
package com.jwzhangjie.test;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class MyListView extends ListView{
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
*****(2)第二种方法:添加完数据后计算ListView中所有Item的高度和间隔线的高度然后重新设置ListView的高度
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
if (listAdapter.getCount() <= 1)
return;
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, null, listView);
view.measure(0,0);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
设置完数据后,调用setListViewHeightBasedOnChildren(listview);
有时候项目里面需要ScrollView嵌套ListView,但是正常下ListView只会显示一行多一点,解决方法就是填充ListView数据后
重新计算ListView的高度,这里有两种方法来实现。
***(1)第一种方法:重写ListView
package com.jwzhangjie.test;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class MyListView extends ListView{
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
*****(2)第二种方法:添加完数据后计算ListView中所有Item的高度和间隔线的高度然后重新设置ListView的高度
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
if (listAdapter.getCount() <= 1)
return;
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, null, listView);
view.measure(0,0);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
设置完数据后,调用setListViewHeightBasedOnChildren(listview);