ScrollView与ListView,ExpandableListView共存

1.ListView与ScrollView共存,可以使用下面的函数来自动调节ListView的大小

public static void setListViewHeightBasedOnChildren(ListView listView)
{
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
{
return;
}

int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
for (int i = 0; i < listAdapter.getCount(); i++)
{
View listItem = listAdapter.getView(i, null, listView);
if (listItem instanceof ViewGroup)
{
listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT));
}

listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}


LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}

2.ExpandableListView与ScrollView共存时,调用下面的方法,设定ExpandableListView的大小

public static void setExpandableListViewHeightBasedOnChildren(ExpandableListView listView)
{
// 获取ExpandableListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
{
// pre-condition
return;
}

int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++)

// listAdapter.getCount()返回数据项的数目
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0); // 计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
}

ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
// listView.getDividerHeight()获取子项间分隔符占用的高度
// params.height最后得到整个ListView完整显示需要的高度

listView.setLayoutParams(params);
}


3.注意:上面两种方法设置之后,有可能会出现一些误差,可以通过修改for中的值来控制;

除此之外,设置之后,ScrollView可能不是从头部开始显示,此时可以在Handler中实现使ScrollView跳转到头部显示。

Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.what == 0x1)
{

MyAdapter adapter = new MyAdapter(this,dataList);
listView.setAdapter(adapter);
ListViewUtility.setComemtsListViewHeight(listView);
handler.post(new Runnable()
{
@Override
public void run()
{
scrollView.fullScroll(ScrollView.FOCUS_UP);
}
});

}

}

}

你可能感兴趣的:(ScrollView与ListView,ExpandableListView共存)