【发布时间】:2010-10-17 14:25:47
【问题描述】:
为了让我的应用程序的用户知道当前哪个字段具有焦点,我正在尝试根据当前状态更改某些字段的背景颜色,但是,我在理解 Android 的颜色状态列表资源时遇到了麻烦:
我找到了示例(抱歉,URL 不再有效),如果我尝试 exactly 相同,即如果我想调整 textColor ,事情做 工作。但是,如果我只尝试略有不同的东西,即调整背景颜色,那么事情不起作用,我不明白为什么?为什么这么不一致???
为了更容易理解我想要做什么,我附上了我的杂项。 .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>
如果我按此处所示运行它,它会起作用,即我得到一个按钮,其文本颜色会根据按钮是否聚焦、按下等而变化。
如果我取消注释下部按钮,我只是翻转了 textColor 和背景的属性值,我得到一个异常,说明
... <item> tag requires a 'drawable' attribute or child tag defining a drawable
我到底错过了什么?为什么该颜色状态列表可以作为文本颜色但不能作为背景颜色?如何根据视图的状态指定视图的背景颜色?
【问题讨论】:
标签: android colors android-linearlayout