要给我的应用程序的用户指示哪个字段当前有焦点我试图根据当前状态更改一些字段的背景颜色,但是,我有问题了解Android的颜色状态列表资源:如何在颜色状态列表资源中指定背景颜色?
我发现的例子(对不起,URL不再工作),如果我尝试完全相同相同,即如果我想适应文字颜色,事情做工作。但是,如果我尝试一个只有略有不同的事情,即适应背景颜色,东西不要工作,我不明白为什么?为什么这是如此不一致?
为了让我更容易理解我想要做的事情,我追加了我的杂项。 .xml文件:
的AndroidManifest.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mmo.android.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Test"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
的Test-Activity
:
package mmo.android.test;
import android.app.Activity;
import android.os.Bundle;
public class Test extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
的res/values/strings.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Test!</string>
<string name="app_name">Test</string>
</resources>
res/color/button_test_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="#f0f"/> <!-- pressed -->
<item android:state_focused="true" android:color="#ff0"/> <!-- focused -->
<item android:color="#000"/> <!-- default -->
</selector>
最后我res/layout/main.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="foobar"
android:textColor="@color/button_test_color"
android:background="#f00"
/>
<!--
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="foobar"
android:textColor="#f00"
android:background="@color/button_test_color"
/>
-->
</LinearLayout>
如果我运行这个如下图所示,它的工作原理,即我得到它的文本颜色取决于按钮是否被聚焦变化的按钮,按下等
如果我取消了下按键,在这里我只是翻转属性值文字颜色和背景我得到一个异常,说明
... <item> tag requires a 'drawable' attribute or child tag defining a drawable
我在这里错过了什么?为什么该颜色状态列表可接受为文本颜色,但不能作为背景颜色?如何根据视图的状态指定视图的背景颜色?
更多inf。在使用drawable资源时,这个[问题已经被问过](http://stackoverflow.com/questions/3506319/android-linearlayout-with-color-resource-what-am-i-doing-wrong)。 – frayser 2010-10-17 21:48:20
我不知道为什么这个答案被标记为正确。提问者似乎遵循了[Android文档](http://developer.android.com/guide/topics/resources/color-list-resource.html),这表明@color应该可以正常工作res/color目录并通过文件名引用。 – JulianSymes 2013-06-17 16:13:56
我甚至更惊讶这是当它不工作时所选择的答案。 -1 – Sotti 2014-11-29 00:12:50