1、直接上代码xml文件
2、在.Java代码中写入
<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"
>
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
出现的情况是
2、在.Java代码中写入
private ListView listView;
private MyAdapter adapter;
private List<Message> list;
private ScrollView scrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
scrollView = (ScrollView) findViewById(R.id.scrollView);
//获取数据源
initData();
//创建适配器
adapter = new MyAdapter(MainActivity.this, list);
listView.setAdapter(adapter);
//设置scrollView滚动的位置
scrollView.smoothScrollTo(0, 0);
//给listView这是高度
setListViewHeight(listView);
}
//给主件设置高度
private void setListViewHeight(ListView listView) {
//拿到给listVIew填充数据的adapter对象
ListAdapter adapter = listView.getAdapter();
if(adapter==null){
return;
}
int totalHeight = 0;//所有item 的高度
for(int i=0;i<adapter.getCount();i++){
//获取当前下标为i的item的view对象
View view= adapter.getView(i, null, listView);
//测量view
view.measure(0, 0);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight()*(adapter.getCount()-1));
listView.setLayoutParams(params);
}
运行后的结果