The accepted answer won't actually work. The answer should have been updated.
If you look at why mAppBarLayout.setTargetElevation(0)
is deprecated. it states that:
@deprecated target elevation is now deprecated.
AppBarLayout's elevation is now controlled via a {@link android.animation.StateListAnimator}.
This method now always returns 0.
So to programmatically set the appbar layout you can only do it by creating a StateListAnimator
such as appbar_state_unelevated_animator
at the animator
res folder:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<objectAnimator
android:propertyName="elevation"
android:valueTo="4dp"
android:valueType="floatType"
android:duration="100"/>
</item>
then loading it in code like so:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
appbar.stateListAnimator = AnimatorInflater.loadStateListAnimator(applicationContext, R.animator.appbar_state_unelevated_animator)
}
If I'm not mistaken you could also create a StateListAnimator
by code but don't take my word for it.
Update:
In my experience when you set the
app:elevation="//Any DP value//"
The Shadow of the app bar will be lost. Simple remove that line to get the appbar shadow again.