Created
October 26, 2014 16:41
-
-
Save RajeshBatth/374557d0ee6f8015e75c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyViewPager extends ViewPager { | |
private BgDrawableAdapter mAdapter; | |
private Paint mFgPaint; | |
private Bitmap mBitmap, mNextBitmap; | |
private Paint mBgPaint; | |
private int mAlpha; | |
public MyViewPager(Context context) { | |
super(context); | |
} | |
public MyViewPager(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
init(); | |
} | |
private void init() { | |
setOnPageChangeListener(mListener); | |
mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
mFgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
} | |
private int mPosition; | |
private float mPositionOffset; | |
private OnPageChangeListener mListener = new OnPageChangeListener() { | |
@Override | |
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { | |
//Reset bitmaps on page change | |
if (mPosition != position) { | |
mBitmap = null; | |
mNextBitmap = null; | |
Log.i(LOG_TAG, "Reset"); | |
} | |
mPosition = position; | |
mPositionOffset = positionOffset; | |
} | |
@Override | |
public void onPageSelected(int position) { | |
} | |
@Override | |
public void onPageScrollStateChanged(int state) { | |
} | |
}; | |
@Override | |
protected void dispatchDraw(Canvas canvas) { | |
//Draw Background | |
if (mNextBitmap == null && mPositionOffset != 0) { | |
BitmapDrawable drawable = | |
(BitmapDrawable) getResources().getDrawable(mAdapter.getDrawableResource(mPosition + 1)); | |
mNextBitmap = drawable.getBitmap(); | |
Log.i(LOG_TAG, "Created the background"); | |
} | |
if (mNextBitmap != null) { | |
canvas.drawBitmap(mNextBitmap, null, canvas.getClipBounds(), mBgPaint); | |
} | |
//Draw Foreground | |
if (mBitmap == null) { | |
BitmapDrawable mDrawable = | |
(BitmapDrawable) getResources().getDrawable(mAdapter.getDrawableResource(mPosition)); | |
mBitmap = mDrawable.getBitmap(); | |
Log.i(LOG_TAG, "Created the foreground"); | |
} | |
mAlpha = (int) ((1 - mPositionOffset) * 255); | |
mFgPaint.setAlpha(mAlpha); | |
canvas.drawBitmap(mBitmap, null, canvas.getClipBounds(), mFgPaint); | |
super.dispatchDraw(canvas); | |
} | |
@Override | |
public void setAdapter(PagerAdapter adapter) { | |
if (adapter instanceof BgDrawableAdapter) { | |
super.setAdapter(adapter); | |
mAdapter = (BgDrawableAdapter) adapter; | |
} else { | |
throw new IllegalArgumentException("Adapter should implement BgDrawableAdapter"); | |
} | |
} | |
public static interface BgDrawableAdapter { | |
public int getDrawableResource(int position); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment