Marcel50506 Marcel50506 - 3 months ago 12
Android Question

Android background not correctly applied on first instance

I have a very simple layout, simply two buttons below each other. On both buttons I set a drawable layer-list as background, containing the selectableItemBackground causing a ripple effect on the buttons.

A weird bug occurs: on the first button, the ripple effect doesn't happen, but on the second button it does. How can this be explained, or can it be a bug in Android/Support Libraries?

Setting clickhandlers doesn't change anything, the behaviour stays the same.

See example gif below, and XML code below that.

GIF of behaviour

main_activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/first_button"
android:text="First Button"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_margin="12dp"
android:background="@drawable/white_selectable_button"/>
<Button
android:id="@+id/second_button"
android:text="Second Button"
android:layout_width="match_parent"
android:layout_margin="12dp"
android:layout_height="48dp"
android:background="@drawable/white_selectable_button"/>
</LinearLayout>


white_selectable_button.xml (in res/drawable):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white"/>
<item android:drawable="?attr/selectableItemBackground"/>
</layer-list>


It appears that this drawable is applied to the button, since when setting the color to red, the button actually appears red. Only the selectableItemBackground ripple isn't applied.

I've tested this with design support libraries 24.1.1, 23.4.0 and 23.2.0, on all versions, this doesn't change anything.

EDIT: Filed bug report to Android bug tracker: https://code.google.com/p/android/issues/detail?id=219620

Answer

Took your code and confirmed it also does not work on my device. I submitted this as a bug against the Android Support Library. So eventually it will get fixed.

In the meantime, I figured out an easy workaround to fix the bug. All you need to do is add an invisible dummy Button before the other two as it appears this bug only affects the first button. You can eventually remove this once its fixed by Google.

 <Button
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/white_selectable_button"
        android:visibility="gone" />
Comments