I have created a scrollview and an imageview is placed within it. I\'d like on scroll for it to resize in the same fashion it is done in the image below but so far I\'ve had lit
There is simple example below that shows how to achieve parallax effect.
First, put your ImageView
and other views into FrameLayout
:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/flWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/contactPic"
android:layout_width="match_parent"
android:layout_height="@dimen/contact_photo_height"
android:scaleType="centerCrop"
android:src="@drawable/stock" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/contact_photo_height">
<!-- Other Views -->
</LinearLayout>
</FrameLayout>
</ScrollView>
LinearLayout
's top margin is equal to the ImageViews
's height (@dimen/contact_photo_height
in our example).
Then we should listen scroll position of the ScrollView
and change the position of ImageView
:
@Override
protected void onCreate(Bundle savedInstanceState) {
<...>
mScrollView = (ScrollView) findViewById(R.id.scrollView);
mPhotoIV = (ImageView) findViewById(R.id.contactPic);
mWrapperFL = (FrameLayout) findViewById(R.id.flWrapper);
mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ScrollPositionObserver());
<...>
}
private class ScrollPositionObserver implements ViewTreeObserver.OnScrollChangedListener {
private int mImageViewHeight;
public ScrollPositionObserver() {
mImageViewHeight = getResources().getDimensionPixelSize(R.dimen.contact_photo_height);
}
@Override
public void onScrollChanged() {
int scrollY = Math.min(Math.max(mScrollView.getScrollY(), 0), mImageViewHeight);
// changing position of ImageView
mPhotoIV.setTranslationY(scrollY / 2);
// alpha you could set to ActionBar background
float alpha = scrollY / (float) mImageViewHeight;
}
}