Skip to content

Instantly share code, notes, and snippets.

@hangox
Created January 7, 2015 07:14
Show Gist options
  • Select an option

  • Save hangox/8ddc69b5dc6658b100db to your computer and use it in GitHub Desktop.

Select an option

Save hangox/8ddc69b5dc6658b100db to your computer and use it in GitHub Desktop.
一个自适应内部内容的ViewPager写法,缺陷就是,过渡是闪烁的
package com.chezanw.wz.widget;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.hangox.xlog.XLog;
/**
* Created With Android Studio
* User 4
* Date 2014/12/19
* Time 15:50
*/
public class MyViewPager extends ViewPager {
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
}
// @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//下面遍历所有child的高度
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
XLog.i(child.getMeasuredHeight()+"");
}
ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
int cItemIndex = getCurrentItem();//选取当前显示的View作为现在的高度
if (cItemIndex >= 0 || cItemIndex < getChildCount()) {
View view = getChildAt(cItemIndex);
if (view != null) {
int height = getChildAt(cItemIndex).getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// int height = 0;
// //下面遍历所有child的高度
// 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) //采用最大的view的高度。~
// height = h;
// }
// heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
// MeasureSpec.EXACTLY);
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment