0
我试图用选择器以编程方式更改某些按钮的背景。 我有两个不同的选择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"
这是指一个drawables资源文件,但没有成功。
我觉得你可以考虑看看这个让我的问题是什么更好的画面: https://youtu.be/y2xKHz3bgfs
编辑: 好像选择总是选择被按下的按钮和下一个按钮具有相同的可绘制背景。
这不是真的是我问的主要活动。您可以在视频中看到选择器出现问题。 –
.getColor已弃用麻烦使用ContextCompat.getColor(上下文,R.color.my_color) – headshoT
对于绘制对象 ContextCompat.getDrawable(getApplicationContext(),R.drawable.back_arrow) 对于彩色 ContextCompat.getColor(getApplicationContext() ,R.color.red) – headshoT