解决ScrollView中包含ListView,导致ListView显示不全

ScrollView 中包含 ListView 的问题 : ScrollView和ListView会冲突,会导致ListView显示不全

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="2dp"
    android:fillViewport="true" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/id0"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
       <TextView
            android:id="@+id/id1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/id2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/border" />
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</ScrollView>
网上有人说需要设置ScrollView的一个属性,但我去掉此设置之后依然是可正常显示的
 
另外ListView的Item的布局要是LinearLayout。(刚开始设置的是RelativeLayout,结果在动态设置高度时报空指针异常)
 
接着就在java文件中设置ListView的高度了
/***  
     * 动态设置listview的高度  
     * @param 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);  //在还没有构建View 之前无法取得View的度宽。在此之前我们必须选                 measure 一下.  
            totalHeight += listItem.getMeasuredHeight();  
            Log.i("xxxxxxxx listItem xxxxxxxxx", i + "  height : " + totalHeight);
        }    
        ViewGroup.LayoutParams params = listView.getLayoutParams();    
        params.height = totalHeight    
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));    
        // listView.getDividerHeight()获取子项间分隔符占用的高度    
        listView.setLayoutParams(params);    
    }    
在ListView的 setAdapter(adapter)方法后调用上面的方法。
 
做完这些工作之后,就可在ScrollView中完整的显示ListView了。
 
当然,不推荐这种嵌套的方式,完全可以使用itenType来实现

转载于:https://www.cnblogs.com/wenhui92/p/6242390.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值