禁用和启用的自定义按钮颜色

时间:2012-04-06 11:35:28

标签: android layout

我有一个Android应用程序,它有一个按钮,我希望它在被禁用时有黑色文本和背景,然后是启用时带有白色书写的绿色背景。

我已启用启用和禁用工作,但如果我更改颜色按钮保持不变,无论其状态如何。

我已经读过我需要使用自定义选择器手动设置颜色,这是我到目前为止所得到的:

res / drawable中的

continuebutton.xml :(绿色在/res/values/colors.xml中声明)

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item 
android:state_enabled="false"
    android.textColor ="@android:color/black"
    android:drawable="@android:color/black" />
<item 
    android:state_enabled="true"
    android.textColor ="@android:color/white"
    android:drawable="@color/green" />

在布局xml文件中继续按钮:

 android:id="@+id/continueButton"
   android:layout_width="200dp"
    android:layout_height="55dp"  android:layout_gravity="center" android:paddingTop="10dp" android:textSize="18dp" 
    android:text="@string/continueButton" android:background="@drawable/continuebutton" />

我认为我在continuebutton.xml文件中做错了,但我不确定如何修复它。

非常感谢任何帮助!

由于

更新

我有背景改变颜色,最后一个问题是解决的是文本颜色,无论该按钮是禁用还是启用,都保持黑色(启用时应为白色)。

我是否需要在res / drawable中为文本颜色创建一个新的xml文件?

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

删除属性

android:src="@drawable/continuebutton"

并使用

android:background="@drawable/continuebutton"

在运行时,您可以通过

更改背景图像
myButton.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.myfirstbg));
myButton.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.mysecondbg));

如果你想使用背景颜色删除两个属性`

android:src="@drawable/continuebutton"
android:background="@drawable/continuebutton"

并使用此

更改背景颜色
myButton.setBackgroundColor(Color.BLUE);
myButton.setBackgroundColor(Color.GREEN);

答案 1 :(得分:0)

您必须将文件添加到res/color文件夹中。

您有一些“状态”值可用。有关启用/禁用的信息,请参见android:state_enabled

mybutton_color.xml文件

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#fff"/> <!-- pressed -->
    <item android:state_focused="true" android:color="#fff"/> <!-- focused -->
    <item android:state_enabled="false" android:color="#000"/> <!-- disabled -->
    <item android:color="#fff"/> <!-- default -->
</selector>

您认为使用android:textColor

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    android:textColor="@color/mybutton_color" />

如此处所述:https://developer.android.com/guide/topics/resources/color-list-resource