コンピュータクワガタ

かっぱのかっぱによるコンピュータ関連のサイトです

Androidアプリ入門 No.20 ImageButtonの使い方

今風に書き直した記事がありますので、合わせて参照ください。
blog.webarata3.link

ImageButton

ImageButtonの使い方

ImageButtonを使用するためには、通常時のボタン、フォーカスがが当たっている際の画像、押したときの画像の3つが必要になる。
たとえば、以下の3つの画像を用意する。それぞれ、test_normal.png、test_focused.png、test_pressed.pngという画像にする。



そして、res/drawable/selector.xmlという以下のファイルを用意する。

<?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/test_pressed" />
    <item android:state_focused="true"
          android:drawable="@drawable/test_focused" />
    <item android:drawable="@drawable/test_normal" />
</selector>

ここで、ボタンの状態により表示する画像を設定する。画像の置き場所はImageViewと同様。
その設定を反映させたmain.xmlは以下となる。srcにselectorを指定する。

<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/selector"
        />
</LinearLayout>

実行結果は以下。