android中scrollview中嵌入listview 产生的滚动问题

来源:互联网 发布:java中的file类 编辑:程序博客网 时间:2024/06/04 17:43

android中使用ScrollView内嵌ListView共存会存在滚动的问题,并且ListView只显示一个半Item。

当ListView的高度设定一定的值时,ListView同样地会显示对应的高度的Item。

因此我们可以计算出这个ListView的总高度,再将它设置到ListView中,这样就解决了之前的问题。

代码如下:

public void setListViewHeightBasedOnChildren(ListView listView) {      ListAdapter adapter = listView.getAdapter();       if (adapter == null) {          return null;      }      int height = 0;      for (int i = 0; i < adapter.getCount(); i++) {          View v = adapter.getView(i, null, listView);          v.measure(0, 0);          height += v.getMeasuredHeight();      }      ViewGroup.LayoutParams ps = listView.getLayoutParams();      ps.height = height + (listView.getDividerHeight() * (adapter.getCount() - 1));      ((MarginLayoutParams)ps).setMargins(15, 15, 15, 15);    listView.setLayoutParams(ps);  } 
其中xml布局如下:

<ScrollView 
        xmlns:android="http://schemas.android.com/apk/res/android"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:fadingEdge = "none"         >       <LinearLayout android:gravity="center_horizontal"           android:orientation="vertical"           android:layout_width="fill_parent"           android:layout_height="fill_parent">       <ListView           android:id="@+id/listView"           android:layout_width="fill_parent"           android:layout_height="fill_parent"           android:dividerHeight="0.0dip"           android:fadingEdge="none"        />   </LinearLayout></ScrollView>



0 0
原创粉丝点击