ScrollView+listView共同使用时,ListView全部展开

ScrollView+listView共同使用时,ListView全部展开并不影响滑动,解决方案:

一.动态设置listview的高度
import android.view.ViewGroup.LayoutParams;

//动态根据listView中item的高度计算listView的高度:
public void setHeight(){  
    int listViewHeight = 0;  
    int adaptCount = listAdapter.getCount();  
    for(int i=0;i<adaptCount;i++){  
        View temp = listAdapter.getView(i,null,lsComment);  
        temp.measure(0,0);  
        listViewHeight += temp.getMeasuredHeight();  
    }  
    LayoutParams layoutParams = listView.getLayoutParams();  
    layoutParams.width = LayoutParams.FILL_PARENT;  
    layoutParams.height = listViewHeight + (listView.getDividerHeight() * (adaptCount - 1)); 
    listView.setLayoutParams(layoutParams);  
}

上面这个方法就是设定ListView的高度了,在为ListView设置了Adapter之后使用,就可以解决问题了。
    但是这个方法有个两个细节需要注意:
        一是Adapter中getView方法返回的View的必须由LinearLayout组成,因为只有LinearLayout才有measure()方法,如果使用其他的布局如RelativeLayout,在调用listItem.measure(0,0);时就会抛异常,因为除LinearLayout外的其他布局的这个方法就是直接抛异常的,没理由…。我最初使用的就是这个方法,但是因为子控件的顶层布局是RelativeLayout,所以一直报错,不得不放弃这个方法。
        二是需要手动把ScrollView滚动至最顶端,因为使用这个方法的话,默认在ScrollView顶端的项是ListView,具体原因不了解,可以在Activity中设置:

 ScrollView sv = (ScrollView) findViewById(R.id.act_solution_1_sv);

二.自定义可适应ScrollView的ListView

自定义一个类继承自ListView,通过重写其onMeasure方法,达到对ScrollView适配的效果。

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class ListViewForScrollView extends ListView {
    public ListViewForScrollView(Context context) {
        super(context);
    }
    public ListViewForScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ListViewForScrollView(Context context, AttributeSet attrs,
        int defStyle) {
        super(context, attrs, defStyle);
    }
    
    /**
     * 重写该方法,达到使ListView适应ScrollView的效果
     */
	@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
        MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

这个方法也是默认显示的首项是ListView,需要手动把ScrollView滚动至最顶端。

sv = (ScrollView) findViewById(R.id.act_solution_4_sv);
sv.smoothScrollTo(0, 0);

转载于:https://my.oschina.net/u/2320057/blog/532128

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值