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);