Created
January 17, 2016 09:06
-
-
Save PPartisan/55d23d482522c7e4447a to your computer and use it in GitHub Desktop.
Quick way of implementing a parallax effect for a ViewPager with two pages
This file contains 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 MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager); | |
MyViewPagerAdapter adapter = new MyViewPagerAdapter(getSupportFragmentManager()); | |
viewPager.setAdapter(adapter); | |
DisplayMetrics metrics = getDefaultDisplayMetrics(this); | |
//Fullscreen background ImageView, with MATCH_PARENT params for width and height. | |
ImageView parallaxBackground = (ImageView) findViewById(R.id.parallax_background); | |
parallaxBackground.getLayoutParams().width = ((int)(metrics.widthPixels * 1.1F)); | |
final int offsetSize = ((int)(metrics.widthPixels * 1.1F) - metrics.widthPixels); | |
parallaxBackground.setX(-offsetSize); | |
ParallaxListener listener = new ParallaxListener(parallaxBackground, offsetSize); | |
viewPager.addOnPageChangeListener(listener); | |
} | |
private static DisplayMetrics getDefaultDisplayMetrics(Context context) { | |
return context.getResources().getDisplayMetrics(); | |
} | |
static class ParallaxListener implements ViewPager.OnPageChangeListener { | |
private ImageView mImageView; | |
private final int offsetSize; | |
ParallaxListener(ImageView imageView, int offsetSize) { | |
mImageView = imageView; | |
this.offsetSize = offsetSize; | |
} | |
@Override | |
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { | |
if (position == 1) { | |
positionOffset = 1; | |
} | |
int offset = (int) (-offsetSize + (offsetSize * positionOffset)); | |
mImageView.setX(offset); | |
} | |
@Override | |
public void onPageSelected(int position) {} | |
@Override | |
public void onPageScrollStateChanged(int state) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment