Android CheckBoxの画像を変更する その1

ここ「Android Wiki ボタンの画像変更(CheckBox,RadioButton)」を見れば一発だけど、一応メモ。

画像を用意する

まずチェックボックスの4つの状態を表す画像を用意します。
画像はres/drawable-nodpiに配置します。
  • チェックONかつ選択されていない状態の画像 [checkbox_checked]


  • チェックONかつ選択されている状態の画像 [checkbox_checked_selected]


  • チェックOFFかつ選択されていない状態の画像 [checkbox_unchecked]


  • チェックOFFかつ選択されている状態の画像 [checkbox_unchecked_selected]

画像を定義する

res/drawableフォルダに「custom_checkbox.xml」を作成します。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- チェックON かつ 選択されている状態 -->
    <item
        android:state_checked="true"
        android:state_pressed="true"
        android:drawable="@drawable/checkbox_checked_selected" />
    <!-- チェックON かつ 選択されていない状態-->
    <item
        android:state_checked="true"
        android:drawable="@drawable/checkbox_checked" />
    <!-- チェックOFF かつ 選択されている状態-->
    <item
        android:state_checked="false"
        android:state_pressed="true"
        android:drawable="@drawable/checkbox_unchecked_selected" />
    <!-- チェックOFF かつ 選択されていない状態-->
    <item
        android:state_checked="false"
        android:drawable="@drawable/checkbox_unchecked" />
</selector>

styleを定義する

res/values/styles.xmlを編集し、CheckBoxに設定するスタイルを追記します。
<resources>
    <style name="CustomCheckBox" parent="android:Widget.CompoundButton.CheckBox">
        <item name="android:button">@drawable/custom_checkbox</item>
    </style>
</resources>

CheckBoxにStyleを設定する

res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <CheckBox
        android:id="@+id/CheckBox03"
        style="@style/CustomCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox" />

    <CheckBox
        android:id="@+id/CheckBox02"
        style="@style/CustomCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="CheckBox" />

</LinearLayout>

実行してみた

ハイ。ちゃんとできました。

そしてハマった。

で、以前コチラ「Android GridView CheckBox付きの画像を表示」で作成したチェックボックスに適用してみたのですよ。
私はCheckBoxを画像の右上に配置したいのに、これ以上ガンとして動きません。
レイアウトをいじり倒しても動かないし・・・結構ハマりました・・・

実はCheckBox画像の右横にもう一つ画像があるのですよ。
次回はこの画像をどうにかしたいと思います。

0 件のコメント: