[Android] Button:画像付きテキストのボタンを表示する

Button
はボタンのラベルにテキストのみではなく、画像を表示させることができます。ここでは画像付きテキストのボタンを表示する方法について説明します。
広 告
目次
前提条件
動作確認端末
1. レイアウトXMLで画像付きテキストのボタンを表示する
レイアウトXMLで画像付きテキストのボタンを表示させるために、<Button>
タグを使用します。テキスト、画像を設定するための属性は以下の表のとおりです。
属性名 | 説明 |
android:text | テキストを設定します |
android:drawableLeft | テキストの左に画像を設定します |
android:drawableTop | テキストの上に画像を設定します |
android:drawableRight | テキストの右に画像を設定します |
android:drawableBottom | テキストの下に画像を設定します |
android:drawableStart | テキストの先頭に画像を設定します |
android:drawableEnd | テキストの末尾に画像を設定します |
以下にサンプルコードを示します。
<Button>タグを使った画像付きテキストのボタン
<Button android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:drawableLeft="@android:drawable/ic_menu_send" />
Note :
@android:drawable/ic_menu_send
はAndroidシステムが持つリソースを参照しています。
実行すると以下のような画面になります。

2. Javaコードで画像付きテキストのボタンを表示する
レイアウトXMLで画像付きテキストのボタンを表示させるために、<Button>
タグを使用します。テキスト、画像を設定するための属性は以下の表のとおりです。
Javaコードで実行する場合は、Buttonクラスを使用します。setText()メソッドを使ってテキストを設定、setCompoundDrawablesWithIntrinsicBounds()メソッドを使って画像を設定することができます。
以下がサンプルコードです。
Buttonクラスを使った画像付きテキストのボタン
final Button button = (Button) findViewById(R.id.button_send); button.setText(getString(R.string.button_send)); button.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_send, 0, 0, 0);
setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)
第一引数から順番にテキストの左、上、右、下、に表示したい画像のリソースIDを指定します。表示させたくない場合は0を指定します。実行すると以下のような画面になります。

3. 画像とテキストの間隔を調整する
テキストとボタンの間隔の設定する場合は、<Button>
タグのandroid:drawablePadding属性を使います。設定値がテキストと画像の間の長さになります。
以下がサンプルコードです。
android:drawablePadding属性を使ったサンプルコード
<Button android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:drawableLeft="@android:drawable/ic_menu_send" android:drawablePadding="30dp"/>
実行すると以下のようになります。
