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

本文介绍了解决Android中ScrollView内嵌ListView时出现的滚动问题的方法。通过计算ListView的总高度并设置到ListView中,使得ListView能正确展示所有Item。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值