要給我的應用程序的用戶指示哪個字段當前有焦點我試圖根據當前狀態更改一些字段的背景顏色,但是,我有問題了解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