机器人按钮与不同的背景色机器人、背景色、按钮、不同

2023-09-13 02:33:45 作者:6.愿时光盗不走你

我要改变使用选择-XML文件按钮的背景颜色。我的做法基本上是从实例底部此页面一:http://developer.android.com/guide/topics/resources/color-list-resource.html

i want to change the background-color of a button using a selector-xml-file. My approach is basically the one from the example at the bottom this page: http://developer.android.com/guide/topics/resources/color-list-resource.html

我有一个RES /彩色/ button_text.xml它看起来是这样的:

i have a res/color/button_text.xml which looks like this:

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

和我的布局包含下列code:

and my layout contains the following code:

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

(**只是没有告诉你,我使用的android:背景,而不是机器人:文本颜色)

(** is only there to show you that i use android:background instead of android:textcolor)

这code崩溃。它说:二进制XML文件中的行#4标签需要'绘制'属性或子标签定义绘制但是,如果我尝试用机器人:。文字颜色在正常工作上面的链接描述所以它必须是后台的问题我。不希望创建一个9patch,PNG,如果它不是必需的(基本上我只是需要一个点击的矩形,所以我使用了彩色背景按钮)

this code crashes. it says "Binary XML file line #4 tag requires 'drawable' attribute or child tag defining drawable. But if I try it with android:textColor as described in the above link it works fine. So it has to be the background issue. I don't want to create a 9patch-png if it's not necessary (basically i just need a "clickable" rectangle so i use a button with a colored background)

推荐答案

由于您的错误状态,你必须定义的绘制的attibute的项目(出于某种原因,要求当涉及到背景定义),因此:

As your error states, you have to define drawable attibute for the items (for some reason it is required when it comes to background definitions), so:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/red"/> <!-- pressed -->
    <item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
    <item android:drawable="@color/black"/> <!-- default -->
</selector>

另外请注意,绘制的属性不接受裸色值,所以你必须定义颜色资源。创建的 colors.xml 的文件,在 RES /值的文件夹:

Also note that drawable attribute doesn't accept raw color values, so you have to define the colors as resources. Create colors.xml file at res/values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <color name="black">#000</color>
     <color name="blue">#00f</color>
     <color name="red">#f00</color>
</resources>
 
精彩推荐