selector相当于图片选择器,在res下新建个drawable文件夹,把组件的背景设成对应你建的xml文件名
下面是我做的一个简单的例子
项目结构图见附件
btn.xml代码:
- <?xml version="1.0" encoding="utf-8" ?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <!--没有焦点时的图片背景 -->
- <item android:state_window_focused="false" android:drawable="@drawable/a" />
- <!-- 非触摸模式下获得焦点并单击时的背景图片 -->
- <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/b" />
- <!-- 触摸模式下单击时的背景图片 -->
- <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/c" />
- <!-- 选中时的图片背景 -->
- <item android:state_selected="true" android:drawable="@drawable/d" />
- <!-- 获得焦点时的图片背景 -->
- <item android:state_focused="true" android:drawable="@drawable/e" />
- </selector>
- main.xml代码:
- <pre class="xml" name="code"><?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"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button
- android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@drawable/btn"
- ></Button>
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@drawable/btn"
- ></Button>
- </LinearLayout>
- </pre>