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
:
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;
}
}