没有Scrollbar的ListView可以在ScrollView中使用

时间:2013-11-21 08:58:31

标签: android listview scroll

我想在ListView内使用某种ScrollView。该列表具有可变长度,始终可以添加/删除项目。是否有一种简单的方法可以修改默认Android ListView,我是否必须创建自定义ListView

2 个答案:

答案 0 :(得分:6)

xml文件:

<ScrollView 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"
tools:context=".MainActivity" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="19dp"
        android:text="@string/hello_world" />

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_launcher" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

</ScrollView>

内部活动:

public class MainActivity extends Activity {
   private String listview_array[] = { "ONE", "TWO", "THREE", "FOUR", "FIVE",
                 "SIX", "SEVEN", "EIGHT", "NINE", "TEN" };
   ListView myList;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          myList = (ListView) findViewById(R.id.listView);
          myList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listview_array));
          Helper.getListViewSize(myList);

   }
}

助手类:

public class Helper {
    public static void getListViewSize(ListView myListView) {
        ListAdapter myListAdapter = myListView.getAdapter();
        if (myListAdapter == null) {
            //do nothing return null
            return;
        }
        //set listAdapter in loop for getting final size
        int totalHeight = 0;
        for (int size = 0; size < myListAdapter.getCount(); size++) {
            View listItem = myListAdapter.getView(size, null, myListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
      //setting listview item in adapter
        ViewGroup.LayoutParams params = myListView.getLayoutParams();
        params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
        myListView.setLayoutParams(params);
        // print height of adapter on log
        Log.i("height of listItem:", String.valueOf(totalHeight));
    }
}

答案 1 :(得分:0)

ListView应该展开以填充ScrollView中包含的所需垂直区域,这样您就不会有问题。