Android Studio:带有可绘制选择器的按钮在以编程方式应用时显示背景错误



我试图使用选择器以编程方式更改某些按钮的背景。我有两个不同的选择器

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/palette.greyscale.lightgrey" android:state_pressed="false"></item>
<item android:drawable="@color/palette.blue.mid" android:state_pressed="true"></item>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/palette.greyscale.lightgrey" android:state_pressed="false"></item>
<item android:drawable="@color/palette.orange.mid" android:state_pressed="true"></item>


根据布尔值以编程方式应用:

void setUI() {
    int primary;
    Drawable btn_color;
    if (((App) getActivity().getApplication()).isGender_isMale()) {
        primary = getResources().getColor(R.color.palette_blue_mid);
        btn_color = getResources().getDrawable(R.drawable.button_blue);
    }
    else {
        primary = getResources().getColor(R.color.palette_orange_mid);
        btn_color = getResources().getDrawable(R.drawable.button_orange);
    }
btn_speichern.setBackground(btn_color);
btn_teilen.setBackground(btn_color);
btn_offnen.setBackground(btn_color);
}

这是片段 xml 中的一个按钮:

    <Button
        android:id="@+id/btn_speichern"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/button_blue"
        android:text="Speichern"
        android:textColor="@drawable/button_text_color"
        android:textSize="20sp" />

当按下一个按钮时,另一个按钮也会触发选择器。

在片段xml中更改背景时,它可以正常工作。我还尝试删除引用其中一个可绘制对象资源文件的android:background="@drawable/button_blue",但没有成功。

我认为您可以通过查看以下内容更好地了解我的问题是什么:https://youtu.be/y2xKHz3bgfs

编辑:似乎选择器总是选择按下的按钮和具有相同可绘制背景的下一个按钮。

如果你有两个不同的按钮,你可以将onClickListeners附加到每个按钮,然后让onClick调用向你的主要活动发送一条消息,指示按钮被按下

最新更新