ScrollView+listView共同使用时,ListView所有展开并不影响滑动,解决方案:java
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中设置:android
ScrollView sv = (ScrollView) findViewById(R.id.act_solution_1_sv);
自定义一个类继承自ListView,经过重写其onMeasure方法,达到对ScrollView适配的效果。ide
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);