Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bring ImageView in front of Button in android 5?

In android versions previous to lolipop, the following code works and an image is in front of the button. But in android 5 the imageview is put behind the button.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/button"
    android:layout_width="210sp"
    android:layout_height="210sp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@drawable/round_button"
    android:drawablePadding="10dip"
    android:gravity="center_vertical|center_horizontal" />


<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:contentDescription="@string/torch"
    android:src="?attr/imageview" />

 </RelativeLayout>
like image 950
Mehdi Fanai Avatar asked Nov 30 '14 17:11

Mehdi Fanai


1 Answers

The problem appears Android 5.0's elevation property. Apparently, the RelativeLayout Z-axis ordering is tied into elevation. If both widgets have the same elevation, the RelativeLayout will determine the Z-axis order -- you can see that if you were to switch your layout to be both Button widgets, for example. However, if one widget (Button) has an elevation, and another widget (ImageView) does not, the elevation will take precedence.

You can remove the Button elevation via android:stateListAnimator="@null" or by defining your own custom animator. Or, you can add some elevation to your ImageView to get it to be higher on the Z axis than is the Button.

like image 110
CommonsWare Avatar answered Sep 19 '22 20:09

CommonsWare