【问题标题】:Android: Change CheckBoxPreference icon for checked/unchecked programmaticalyAndroid:以编程方式更改选中/未选中的复选框首选项图标
【发布时间】:2012-06-17 20:48:33
【问题描述】:

我有一些 CheckBoxPreferences,我可以通过如下所示的 xml 和 here 更改它们的图标,但由于用户有其他方式触发复选框的操作,而不是直接单击它(即可能在另一个活动中或甚至是另一个应用程序)我希望能够根据与操作一起发生的值更改以编程方式设置图标。例如,如果蓝牙打开,我希望图标是一个图像,而当蓝牙关闭时,我希望它是另一个图像。是否可以以编程方式更改此图像?

<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+android:id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/check_box_icon"
android:clickable="true"
android:focusable="false"
android:/>

【问题讨论】:

  • 不确定是什么问题。更改图像只需使用 chk = (CheckBox) findViewById(android.R.id.checkbox);和 chk .setBackgroundResource(); ?
  • 好吧,以上只是我通过将 android:widgetLayout="@layout/custom_checkbox" 添加到他们的 xml 属性中使用的 CheckBoxPreferences(不是视图)的 xml 布局。我需要通过代码更改这些复选框首选项的复选框图像...

标签: android image checkbox icons checkboxpreference


【解决方案1】:

找到解决方案:

我使用在问题中提供的链接中找到的方法设置选择器,以便我可以根据复选框的当前状态将其与我的所有 CheckBoxPreferences 一起用于不同图像:-

<?xml version="1.0" encoding="utf-8"?>
//This is the xml selector "@drawable/checkbox"
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />
</selector> 

因此,CheckBoxPreference 代码也发生了变化:-

<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content" 
android:text="new checkbox"
android:button="@drawable/checkbox"
android:clickable="true"
android:focusable="false" />

现在,我可以调用 Checkbox.setChecked() 来检查它是否已启用,也可以通过将其设置为 true 或 false 来根据值进行更改。因此,根据 xml 属性,这也会自动更改图标。

【讨论】:

    猜你喜欢
    • 2016-11-05
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2014-11-24
    • 1970-01-01
    • 2016-03-24
    相关资源
    最近更新 更多