如何为所有元素设置相同的选择器?

时间:2012-07-02 10:42:06

标签: android user-interface checkbox css-selectors

我需要有自定义复选框,这并不是那么棘手。我将checkbox_selector设为drawable文件夹:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/checkbox_disabled" /><!-- disabled -->
    <item android:state_checked="false" android:state_pressed="true" android:drawable="@drawable/checkbox_unchecked_focused" /><!-- pressing unchecked box -->
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/checkbox_checked_focused" /><!-- pressing checked box -->
    <item android:state_checked="true" android:drawable="@drawable/checkbox_checked" /><!-- checked box -->
    <item android:state_checked="false" android:drawable="@drawable/checkbox_unchecked" /><!-- unchecked box -->

</selector>

但问题是我制作的每个按钮,我都要添加

<Checkbox
   android:button="@drawable/checkbox_selector" />

尝试谷歌回答一段时间,也许我找不到合适的词语。

我可以说这个应用程序中的每个复选框都应该使用这个@ drawable / checkbox_selector吗?

编辑: 在styles.xml中说出

<style name="customCheckBox">
   <item android:button>@drawable/checkbox_selector</item>
</style>

在Android 2.3.3中为我工作 但是当我尝试使用Android 4.0.3时,它无效。任何想法为什么会这样?

2 个答案:

答案 0 :(得分:1)

您可以为此目的使用样式: 只需在style.xml中设置:

 <style name="CustomCheckBox" >
    <item name="android:button">"@drawable/checkbox_selector</item>
 </style>

然后只需将您的主题应用到所有Checkbox,执行此操作:

 <Checkbox style="@style/CustomCheckBox" />

有关样式的更多参考,请阅读:

http://developer.android.com/guide/topics/ui/themes.html

答案 1 :(得分:1)

您可以在清单中为所有控件定义它们(主题包含您的样式)

android:theme="@style/CustomCheckBox"