这是main.xml的布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MyActivity">
<ScrollView
android:id="@+id/scorllView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lsitview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
这是运行的效果:ListView显示不完全。为什么会产生这样的原因呢?原因是在ScrollView中是无法计算ListView的高度的,所以要让ListView显示完全,得自己计算出ListView的高度才行。
代码如下:
/**
* 计算ListView的高度
*
* @param listView
*/
public void setListViewHeightBasedOnChildren(ListView listView) {
if (listView == null) {
return;
}
ListAdapter listAdapter = listView.getAdapter();//获取ListView的Adapter,因为要通过Adapter
// 获取到每一个item的高度,
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);//因为有measure这个方法,所以ListView Item的布局一定要是LinearLayout的,否则回报NullPointerExeecption
totalHeight += listItem.getMeasuredHeight();//把所有获取到item的高度加起来
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight +
(listView.getDividerHeight() * (listAdapter.getCount() - 1));//最终的ListView的高度
listView.setLayoutParams(params);
}
计算完ListView的高度之后在给ListView设置Adapter之后调用这个方法即可(一定要在设置完Adapter之后,否则是无法获取item的高度的)
mAdapter = new MyAdapter(mList);
mListView.setAdapter(mAdapter);
setListViewHeightBasedOnChildren(mListView);
再次运行效果入图:
现在在布局文件中加入一个LinearLayout,里面放入一个TextView,代码如下
<ScrollView
android:id="@+id/scorllView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:background="#00ff00"
android:layout_height="40dp">
<TextView
android:textSize="30sp"
android:text="Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="@+id/lsitview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</ScrollView>
再次运行,会发现新加入的LinearLayout没有显示出来,这个界面就从ListView的头部开始显示,如何解决这个问题呢
只需要在初始化ScrollView的地方加入如下代码即可
mScrollView.post(new Runnable() {
@Override
public void run() {
mScrollView.scrollTo(0, 0);
}
});