I want to make a Parallax Scrolling effect of Background Image in an Activity That has view pager, were image should scroll according to ViewPager swipe/slide.
I have already tried to use https://github.com/andraskindler/parallaxviewpager it is not working it shows blank background instead of showing image.
This gif describes my requirement:
Please Help me
Use HorizontalScrollView
and ViewPager.addOnPageChangeListener
method.
Below is Example.
in MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final HorizontalScrollView scrollView = (HorizontalScrollView) findViewById(R.id.scroll_view);
final ImageView imageView = (ImageView) findViewById(R.id.background);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int x = (int) ((viewPager.getWidth() * position + positionOffsetPixels) * computeFactor());
scrollView.scrollTo(x, 0);
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
private float computeFactor() {
return (imageView.getWidth() - viewPager.getWidth()) /
(float)(viewPager.getWidth() * (viewPager.getAdapter().getCount() - 1));
}
});
viewPager.setAdapter(new CustomPagerAdapter(this));
}
}
in layout file (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<HorizontalScrollView
android:id="@+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="@+id/background"
android:layout_width="1000dp"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/image"/>
</FrameLayout>
</HorizontalScrollView>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With