Android 第一次没有正确应用背景

Android background not correctly applied on first instance

我有一个非常简单的布局,只有两个按钮位于彼此下方。在这两个按钮上,我将可绘制图层列表设置为背景,其中包含 selectableItemBackground,从而对按钮产生涟漪效应。

出现一个奇怪的错误:在第一个按钮上,涟漪效果没有发生,但在第二个按钮上却发生了。这怎么解释,或者它可能是 Android/Support 库中的错误?

设置点击处理程序不会改变任何东西,行为保持不变。

请参阅下面的示例 gif,以及下面的 XML 代码。

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(在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>

看来这个drawable被应用到按钮上了,因为当设置颜色为红色时,按钮实际上显示为红色。仅不应用 selectableItemBackground 波纹。

我已经使用设计支持库 24.1.1、23.4.0 和 23.2.0 对所有版本进行了测试,这没有任何改变。

编辑:向 Android 错误跟踪器提交错误报告:https://code.google.com/p/android/issues/detail?id=219620

获取您的代码并确认它在我的设备上也不起作用。我将其提交为 bug against the Android Support Library。所以最终它会得到修复。

与此同时,我想出了一个简单的解决方法来修复该错误。您需要做的就是在其他两个按钮之前添加一个不可见的虚拟按钮,因为看起来这个错误只影响第一个按钮。一旦它被 Google.

修复,你最终可以删除它
 <Button
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/white_selectable_button"
        android:visibility="gone" />