我发现了一个例子(抱歉,URL不再可用),如果我尝试完全相同,即如果我想要适应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和background的属性值,我会得到一个异常,指出
... <item> tag requires a 'drawable' attribute or child tag defining a drawable
我错在哪里了?为什么那个颜色状态列表可以作为文本颜色但不能作为背景颜色?如何根据视图的状态指定视图的背景颜色?