Android selector 组件的状态显示该状态对应的背景图片


Android的selector相当于图片选择器,在res下新建个drawable文件夹,把组件的背景设成对应你建的xml文件名

下面是我做的一个简单的例子

项目结构图见附件

btn.xml代码:

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
  3. <!--没有焦点时的图片背景 -->
  4. <item android:state_window_focused="false" android:drawable="@drawable/a" />
  5. <!-- 非触摸模式下获得焦点并单击时的背景图片 -->
  6. <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/b" />
  7. <!-- 触摸模式下单击时的背景图片 -->
  8. <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/c" />
  9. <!-- 选中时的图片背景 -->
  10. <item android:state_selected="true" android:drawable="@drawable/d" />
  11. <!-- 获得焦点时的图片背景 -->
  12. <item android:state_focused="true" android:drawable="@drawable/e" />
  13. </selector>

main.xml代码:

  1. <pre class="xml" name="code"><?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="@string/hello"
  11. />
  12. <Button
  13. android:id="@+id/button"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:background="@drawable/btn"
  17. ></Button>
  18. <Button
  19. android:id="@+id/button2"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:background="@drawable/btn"
  23. ></Button>
  24. </LinearLayout>
  25. </pre>

相关内容