AndroidアプリのUIを設計する際、イメージボタン(画像ボタン)を用意してonClickイベント時にイメージを切り替えたいことがよくあると思います。
ここでは<selector>タグを利用してxmlの編集のみで簡単に実現する方法をご紹介します。
検証はsdk-1.5で行っています。
ここでは新規で"button1.xml"というファイルを作ります。 ボタン1というのは今回ここで利用するImageButtonです。 さて、この"button1_img.xml"の中に<selector>というダグを使って、通常時とクリックさせた時に表示する画像を登録しておきます。 ここではあらかじめ"/drawable"の下に用意しておいた"green.png"と"blue.png"というイメージを使います。それでは以下のように記述してみましょう。
|
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/blue" /> <item android:drawable="@drawable/green" /> </selector> |
ImageButtonを追加します。この時通常は"background"に直接画像ファイルを指定するのですが、ここでは1の手順で設定した"button1_img.xml"を指定します。
|
<?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" > <ImageButton android:id="@+id/Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/button1" > </ImageButton > </LinearLayout> |
最終的にファイルの構成はこのようになります。
編集が終わったら動作を確認してみましょう!
[通常時] -> [クリック時]