当viewpager只是作为元素在一个页面时,他的高度设置使用match_parent和wrap_content都没有效果,最后的结果就是显示不出来,必须指定固定高度才能显示出来,但是不会自适应,解决办法:
首先是重写Viewpager的onMeasure方法:
package com.yang.Demo;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class WrapContentHeightViewPager extends ViewPager {
private static final String TAG = "WrapContentHeightViewPager";
/** * Constructor * * @param context the context */
public WrapContentHeightViewPager(Context context) {
super(context);
}
/**
* * Constructor * * @param context the context * @param attrs the attribute
* set
*/
public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
Log.i(TAG, "getChildCount()="+getChildCount()+"");
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height)
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
这个时候设置viewpager高度为wrap_content,会看到只显示listview中的一个元素出来,问题是listview的高度也没有自适应内容,这个时候就需要去动态改变listview的高度。
方法:
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
((MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除
listView.setLayoutParams(params);
}
这个方法要在listview设置完adapter之后使用。
参考文章:
解决list:http://blog.csdn.net/h3c4lenovo/article/details/8256472
解决viewpager:http://www.tuicool.com/articles/AbiqYv7 http://www.th7.cn/Program/Android/201406/221640.shtml