【Android】ボタンのdrawableLeft(左側アイコン)をプログラムで動的に設定する方法
はじめに
このチュートリアルでは、Androidアプリのボタン(Button)に対して、テキストの左側に表示されるアイコン(drawableLeft / drawableStart)をプログラムから動的に設定する方法を解説します。
XMLレイアウトでは android:drawableStart 属性で静的に指定できますが、「ユーザーの操作に応じてアイコンを切り替えたい」「条件によって表示を変えたい」といったケースでは、Javaコードからの設定が必要になります。
手順1:新規プロジェクトを作成する
Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成しましょう。
手順2:レイアウトファイル(activity_main.xml)を編集する
res/layout/activity_main.xml に以下のコードを記述します。ここでは RelativeLayout の中央に Button を配置し、初期状態として android:drawableStart でアイコンを設定しています。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button/DrawableLeft"
android:layout_centerInParent="true"
android:drawableStart="@drawable/ic_brush"
android:textSize="24sp"
android:textStyle="bold"/>
</RelativeLayout>
手順3:MainActivity.java を編集する
src/MainActivity.java に以下のコードを記述します。
ポイントとなるのは setCompoundDrawablesWithIntrinsicBounds() メソッドです。このメソッドは、渡された Drawable をそれぞれ「左・上・右・下」の位置に設定できます。左側だけアイコンを表示したい場合は、第1引数に Drawable を渡し、それ以外の引数には null を指定します。
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
Drawable img = button.getContext().getResources().getDrawable( R.drawable.ic_brush );
button.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);
}
}
補足:非推奨APIの代替手段
getResources().getDrawable() は API レベル 22 以降で非推奨(deprecated)となっています。現在の開発では、以下のように ContextCompat.getDrawable() を使用することが推奨されます。
Drawable img = ContextCompat.getDrawable(this, R.drawable.ic_brush); button.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);
手順4:AndroidManifest.xml を確認する
androidManifest.xml は以下のようになっています。特別な権限は不要です。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
アプリを実行して確認する
それでは実際にアプリを実行してみましょう。実機のAndroidスマートフォンをPCに接続していることを前提に説明します。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。デバイス選択画面で自分のスマートフォンを選択すると、端末上にアプリが起動し、ボタンの左側にアイコンが表示されているのが確認できます。

まとめ
ボタンの左側アイコンをコードから変更したい場合は、setCompoundDrawablesWithIntrinsicBounds() メソッドを使用します。右側に設定したい場合は第3引数に、上下に設定したい場合は第2・第4引数に Drawable を渡すことで柔軟に対応できます。アイコンの動的な切り替えなど、UIをインタラクティブにしたい場面でぜひ活用してみてください。
-
【Android】プログラムでアプリケーションを終了する方法|finish()とSystem.exit(0)の使い方
はじめにこの記事では、Androidアプリをプログラム(コード)から終了させる方法を解説します。ボタンをタップするとアプリが終了するシンプルなサンプルアプリを通じて、実装手順をステップごとに見ていきましょう。ステップ1:新規プロジェクトの作成Android Studioを起動し、「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。ステップ2:レイアウトファイルの編集res/layout/activity_main.xml に以下のコードを追加します。このレイアウトには、ガイダンス用のTextViewと、アプリを終了するためのB
-
AndroidでVPNを設定する方法【専用アプリ・OpenVPNの手順を徹底解説】
モバイルデバイスでのブラウジングをもっと安全にしたいと思いませんか?それとも、Netflixの地域制限を回避したいだけでしょうか?VPN(仮想プライベートネットワーク)はそのどちらにも最適な選択肢です。では、AndroidでもVPNを設定できるのでしょうか? この記事では、AndroidデバイスにモバイルVPNをインストールして使う方法、そしてどのVPNを選ぶべきかについて詳しく解説します。さらに、スマートフォンでVPNの使用を避けるべき場面についても触れていきます。 なぜモバイルでVPNを使うのか? VPNといえば、デスクトップPCやルーター向けのツールというイメージが強いかもしれません。で