天天看点

日积月累:ScrollView嵌套ListView只显示一行

在开发的过程当中,由于手机屏幕的大小的限制,我们经常需要使用滑动的方式,来显示更多的内容。在最近的工作中,遇见一个需求,需要将listview嵌套到scrollview中显示。于是乎有了如下布局: 

[html] ​​view plain​​​​copy​​

<linearlayout 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"   

    android:background="#ffe1ff"   

    android:orientation="vertical" >   

    <scrollview   

        android:layout_width="match_parent"   

        android:layout_height="match_parent" >   

        <linearlayout   

            android:layout_width="match_parent"   

            android:layout_height="match_parent" >   

            <listview   

                android:id="@+id/listview1"   

                android:layout_width="match_parent"   

                android:layout_height="match_parent"   

                android:fadingedge="vertical"   

                android:fadingedgelength="5dp" />   

        </linearlayout>   

    </scrollview>   

</linearlayout>   

运行程序,如下结果,无论你如何调整layout_width,layout_height属性,listview列表只显示一列! 

日积月累:ScrollView嵌套ListView只显示一行

在查阅的各种文档和资料后,发现在scrollview中嵌套listview空间,无法正确的计算listview的大小,故可以通过代码,根据当前的listview的列表项计算列表的尺寸。实现代码如下: 

[java] ​​view plain​​​​copy​​

public class mainactivity extends activity {   

    private listview listview;   

    @override   

    protected void oncreate(bundle savedinstancestate) {   

        super.oncreate(savedinstancestate);   

        setcontentview(r.layout.activity_main);   

        listview = (listview) findviewbyid(r.id.listview1);   

        string[] adapterdata = new string[] { "afghanistan", "albania",… … "bosnia"};   

        listview.setadapter(new arrayadapter<string>(this,android.r.layout.simple_list_item_1,adapterdata));   

        setlistviewheightbasedonchildren(listview);   

    }   

    public void setlistviewheightbasedonchildren(listview listview) {   

        // 获取listview对应的adapter   

        listadapter listadapter = listview.getadapter();   

        if (listadapter == null) {   

            return;   

        }   

        int totalheight = 0;   

        for (int i = 0, len = listadapter.getcount(); i < len; i++) {   

            // listadapter.getcount()返回数据项的数目   

            view listitem = listadapter.getview(i, null, listview);   

            // 计算子项view 的宽高   

            listitem.measure(0, 0);    

            // 统计所有子项的总高度   

            totalheight += listitem.getmeasuredheight();    

        viewgroup.layoutparams params = listview.getlayoutparams();   

        params.height = totalheight+ (listview.getdividerheight() * (listadapter.getcount() - 1));   

        // listview.getdividerheight()获取子项间分隔符占用的高度   

        // params.height最后得到整个listview完整显示需要的高度   

        listview.setlayoutparams(params);   

}   

运行结果,ok问题搞定,打完收工! 

日积月累:ScrollView嵌套ListView只显示一行