Control appearance time of setElevation method

I am starting to use ToolBar in my application

I need that when I open my activity the elevation of my Toolbar (located at the top) is 0 to give the impression that there is no Toolbar, and when using scrolling the Toolbar screen it has an elevation of 3 so that it shows the division of Toolbar with the rest of the elements, I have achieved this with the following code:

nScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            if (scrollY != 0){
                toolbar.setBackgroundColor(Color.parseColor("#fcfcfc"));
                toolbar.setElevation(3);
            } else {
                toolbar.setBackgroundColor(Color.parseColor("#fafafa"));
                toolbar.setElevation(0);
            }
        }
    });

It’s just what I need (setElevation () creating a shadow to show the division between my toolbar and the rest of the elements), but the setElevation () method appears very fast and aesthetically looks bad.

I need setElevation to apply within 1 second, is it possible? and How can I do it?

I want to clarify that I do not want delays to start applying setElevation, what I need is that the duration of setElevation is 1 second so that it does not appear suddenly

Answer

Straight from this medium article. Tested it myself and it works:

First create a selector xml file for the elevation of the toolbar, and place in the animator folder (note: not the animation folder):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true">
        <objectAnimator
            android:duration="200"
            android:propertyName="elevation"
            android:valueTo="6dp"          //<---- This is the value for the final elevation!
            android:valueType="floatType" />
    </item>

    <item>
        <objectAnimator
            android:duration="200"
            android:propertyName="elevation"
            android:valueTo="0dp"
            android:valueType="floatType" />
    </item>

</selector>

Add the selector to your toolbar in the layout XML:

android:stateListAnimator="@animator/toolbar_elevation"

And finally add this for your scrollview/recyclerview:

        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                toolbar.setSelected(scrollView.canScrollVertically(-1));
            }
        });

Leave a Reply

Your email address will not be published. Required fields are marked *