5

inside of CollapsingToolbarLayout imageview and i need setAlpha(float) When that scroll up and down:

this is method for get Offset and calculate float by offset:

AppBarLayout.OnOffsetChangedListener:

 @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        float offsetAlpha = (float) (verticalOffset / appBarLayout.getTotalScrollRange());
        imageView.setAlpha(offsetAlpha);
    }

xml layout:

 <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="50dp"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="@android:color/transparent">

      <ImageView
                    android:id="@+id/imageView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:scaleType="centerCrop"
                    app:layout_collapseMode="parallax" />

 </android.support.design.widget.CollapsingToolbarLayout>

but setAlpha does not work. why?

fatiherdem
  • 1,173
  • 6
  • 18
  • 35
Farzad
  • 1,975
  • 1
  • 25
  • 47

2 Answers2

18

Your calculation either gave 0.0 or 1.0.
I tried calculating the offset by getting the fraction of the complete scrollarea.

It's a start and open for improvement.

appbar.addOnOffsetChangedListener(new OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(final AppBarLayout appBarLayout, final int verticalOffset) {
        float offsetAlpha = (appBarLayout.getY() / appbar.getTotalScrollRange());
        imageView.setAlpha( 1 - (offsetAlpha * -1));
    }
})
timr
  • 6,668
  • 7
  • 47
  • 79
1

I know it's a very old question and there is an accepted answer but I figured out a better way to do it as Tim solution does not start from 0.0 to 1.0

override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
    val offsetAlpha =
        1F - ((appBarLayout.totalScrollRange + verticalOffset).toFloat() / appBarLayout.totalScrollRange.toFloat())
    imageView.setAlpha(offsetAlpha);
}

The imageView will totally disappear when AppToolbarLayout fully expanded and if you want to reverse this just remove 1F - from offsetAlpha

Ibrahim Disouki
  • 2,642
  • 4
  • 21
  • 52