说明:很多ScrollView与ListView一起使用过的人都应该知道,到ScrollView嵌套ListView时ListView会自动加滚动,大概只能显示两个Item的高度,很是让人头疼。但是Android貌似并不提倡这两者一起使用,详情请看Android开发文档。

  接下来说一下解决方案:

1、最简单的一种:指定ListView的高度,即android:layout_height='480dp'给ListView的layout_height一个确定的值。这种方法如果只有少量数据还是可行的,但是当有大量数据时就不那么美观了。

2、有一位仁兄重写了ListView,地址:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=46824&extra=page=1&page=1

3、这里还有一个重写的方案:http://www.cnblogs.com/LuoYer/archive/2011/05/07/2039884.html

4、第四种可以完美解决这个问题,就是动态为ListView设置高度,其实原理与第一种的想法一样,就是让ListView“放弃”自己滚动。

先说一下实现思路:动态计算ListView每个Item的高度,然后根据所有的Item的高度设置ListView的总高度。

以下是计算ListView高度的方法。

代码:

public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        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);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        params.height += 5;//if without this statement,the listview will be a little short
        listView.setLayoutParams(params);
    }

 

布局文件:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#44444444">
<ScrollView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content">
    <LinearLayout
            android:id="@+id/ll1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            android:orientation="vertical"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:paddingTop="30dp"
            android:paddingBottom="30dp"
            android:background="#ff888888">
            <TextView
                    android:text="あ"
                    android:textColor="#ffeeeeee"
                    android:textSize="18sp"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"></TextView>
            <ListView
                    android:scrollbars="none"
                    android:stackFromBottom="true"
                    android:id="@+id/lv0"
                    android:layout_width="fill_parent"
                    android:layout_height="20dp"></ListView>
                    </LinearLayout>
</ScrollView>
</LinearLayout>

arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()