参考文章:http://www.360doc.com/content/14/0418/16/11800748_370081990.shtml(安卓泡面)
前一段时间找工作面试的时候被问了一个问题,ScrollView嵌套listView显示不全时改如何解决。当时我时被问蒙了,回来之后各种百度,现在闲下来了也把我总结的方法给大家分享一下。在这只介绍两种简单有效的方法:
一、手动计算listView的高度
/**
* 手动设置ListView的高度
*/
public void setListViewHeight() {
int count = adapter.getCount();
int totalheight = 0;
for (int i = 0; i < count; i++) {
View itemView = adapter.getView(1, null, listView);
measureView(itemView);
totalheight += itemView.getMeasuredHeight();
}
totalheight += listView.getDividerHeight() * (count - 1);
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalheight;
listView.setLayoutParams(params);
}
其实很简单通过listView的adapter获取ItemView,再计算每个ItemView的高度,相加就是ListView的总高度。接下来要做的就是将ListView的LayoutParams参数的高度设置为计算得到的总高度即可。
二、自定义ListView
package com.nado.listviewinscrollview;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* @author ZhangQiong
*
* @date 2016-7-7
*/
public class MyListView extends ListView {
public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyListView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
其实代码也很简单,重写ListView的onMeasure方法修改heightMeasureSpec即可。
最后要说的是方法一只适用于item的布局是LinearLayout的情况,方法二则没有这种限制,两种方法都需要手动将ScrollView滑动到顶部scrollView.smoothScrollTo(0, 0),不然默认从listView的第一个Item开始显示。