How to change app:elevation programmatically
Try with using the following code
ViewCompat.setElevation(View, float)
Following the below link. Here showed how to make elevation on pre-lollipop device
Android AppCompat 21 Elevation
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.
I would like to provide updated and full answer:
switch (state) {
case On:
appBarLayout.setStateListAnimator(AnimatorInflater.loadStateListAnimator(getContext(), R.animator.appbar_elevation_on));
break;
case Off:
appBarLayout.setStateListAnimator(AnimatorInflater.loadStateListAnimator(getContext(), R.animator.appbar_elevation_off));
break;
}
appbar_elevation_on.xml under RES\animator
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="PrivateResource">
<item>
<objectAnimator
android:propertyName="elevation"
android:valueTo="@dimen/design_appbar_elevation"
android:valueType="floatType" />
</item>
</selector>
appbar_elevation_off.xml under RES\animator
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="PrivateResource">
<item>
<objectAnimator
android:propertyName="elevation"
android:valueTo="0dp"
android:valueType="floatType" />
</item>
</selector>