Only one view can be included in a ScrollView .
In Android, a ScrollView is a view group that is used to make vertically scrollable views. A scroll view contains a single direct child only. In order to place multiple views in the scroll view, one needs to make a view group(like LinearLayout) as a direct child and then we can define many views inside it.
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;
}
}
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