[Android] ImageButton:画像ボタンを表示する

ボタンラベルにテキストを表示する通常のボタンはButton
クラスか<Button>
タグを使いますが、ボタンラベルに画像を表示するボタンは、ImageButtonクラスか<ImageButton>
タグを使います。ここではImageButton
の基本的な使い方を説明します。
広 告
目次
前提条件
動作確認端末
1. ImageButtonの概要
画像ボタンを表示させるためにはImageButtonクラスか<ImageButton>
タグを使います。ユーザが画面で ImageButton
をクリックするとクリックイベント実行され、イベントを受け取ることができます。
ImageButtonクラスはImageViewを継承したクラスです。ImageViewクラスのメソッドが使用できます。
2. ImageButtonの使い方
ImageButton
をレイアウトXMLで使用するためには<ImageButton>
タグを使用します。ボタンに表示する画像はandroid:src属性で指定します。
<ImageButton>タグをサンプル使ったコード
<ImageButton android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/button_icon" />
ImageButton
をJavaコードで使用する場合はImageButtonクラスを利用します。
ImageButtonを使ったサンプルコード
final ImageButton imageButton = (ImageButton) findViewById(R.id.button_send);
アプリを実行すると以下のようになります。画像が表示されたボタンが画面に表示されていることがわかります。

3. ImageButtonのクリックイベントを処理する
ImageButtonのクリックイベントを受け取り、イベントを処理する方法はButtonと同じ方法です。詳しくはこちらを参照してください。
以下にサンプルコードだけ示します。まずはandroid:onClick属性を使った方法です。
layout.xml
<ImageButton android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/button_icon" android:onClick="sendMessage" />
MainActivity.java
/** ボタンをクリックした時に呼ばれる */ public void sendMessage(View view) { // ここに処理を記述 }
次はJava側でsetOnClickListener()メソッドを使ったサンプルコードです。
MainActivity.java
final ImageButton imageButton = (ImageButton) findViewById(R.id.button_send); imageButton.setOnClickListener(new View.OnClickListener() { /** ボタンをクリックした時に呼ばれる */ @Override public void onClick(View v) { // ここに処理を記述する } });