为了方便自己以后的使用.也方便小伙伴们.
* 自定义viewpager
* 1.适应高度
* 2.滚动时间
*/
public class CustomViewPager extends ViewPager {
/**
* 设置滚动时间
*/
class MScroller extends Scroller {
public MScroller(Context context) {
super(context);
}
public MScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
public MScroller(Context context, Interpolator interpolator, boolean flywheel) {
super(context, interpolator, flywheel);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
super.startScroll(startX, startY, dx, dy,1000);//这里是设置时间的,也可以用参数传递进来.我闲麻烦就直接手动设置了
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, 1000);
}
}
//------------------------------------
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
try {
Field mField;
mField = ViewPager.class.getDeclaredField("mScroller");
mField.setAccessible(true);
MScroller mScroller = new MScroller(
this.getContext(),
new DecelerateInterpolator());
mField.set(this, mScroller);
} catch (Exception e) {
e.printStackTrace();
}
}
public CustomViewPager(Context context) {
super(context);
try {
Field mField;
mField = ViewPager.class.getDeclaredField("mScroller");
mField.setAccessible(true);
MScroller mScroller = new MScroller(
this.getContext(),
new DecelerateInterpolator());
mField.set(this, mScroller);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//自适应高度
int height = 0;
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);
}
}