转自:http://blog.csdn.net/fu222cs98/article/details/25250471
前 言
问题出现原因:布局中用到了ListView,但是无奈界面上又不是只有ListView 当内容变多时,需要滚动界面。大致布局如下
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@color/app_bg"
- android:orientation="vertical" >
- <ScrollView
- android:id="@+id/scSpace"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
- <ImageView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:src="@drawable/shadow_title" />
- <ListView
- android:id="@+id/listview_personalhealthindex"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:background="@color/app_bg" >
- </ListView>
- </LinearLayout>
- </ScrollView>
- </LinearLayout>
滚动的解决办法:在
- listView.setAdapter(indexAdapter);
- public static void setListViewHeightBasedOnChildren(ListView listView) {
- ListAdapter listAdapter = listView.getAdapter();
- if (listAdapter == null) {
- // pre-condition
- return;
- }
- 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));
- listView.setLayoutParams(params);
- }
现实顶部的解决办法1:初始化的时候就让该界面的顶部的某一个控件获得焦点,滚动条自然就显示到顶部了,代码如下:
- txtBaseMsg.setFocusable(true);
- txtBaseMsg.setFocusableInTouchMode(true);
- txtBaseMsg.requestFocus();
- listview.post(new Runnable() {
- @Override
- public void run() {
- ((ScrollView)findViewById(R.id.scSpace)).scrollTo(0, 0);
- }
- });
参考链接:http://blog.csdn.net/hitlion2008/article/details/6737459