Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidボタンにdrawableLeftをプログラム的に設定する方法

この記事では、Kotlinを使用してAndroidのButtondrawableLeft(テキスト左側に表示されるアイコン画像)をプログラム的に設定する方法を、実際のコード例とともにわかりやすく解説します。

実装手順

ステップ1:新規プロジェクトの作成

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。

ステップ2:レイアウトファイル(res/layout/activity_main.xml)の編集

次に、res/layout/activity_main.xml に以下のコードを記述します。

<?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">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text"
        android:layout_centerInParent="true"
        android:layout_marginTop="20dp"
        android:text="DrawableLeft on Android button"
        android:textColor="@android:color/holo_purple"
        android:textSize="16sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="4dp"
        android:background="@android:color/holo_blue_light"
        android:padding="4dp"
        android:text=" Alarm"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

ステップ3:MainActivity.kt の編集

続いて、src/MainActivity.kt に以下のコードを記述します。ここが今回のポイントとなる部分です。

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val button: Button = findViewById(R.id.button)
        val img: Drawable = button.context.resources.getDrawable(R.drawable.ic_baseline_alarm_24)
        button.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null)
    }
}

ポイント:setCompoundDrawablesWithIntrinsicBounds()は、第1引数から順に「左・上・右・下」のDrawableを指定するメソッドです。今回はアイコンをテキストの左側に表示したいので、第1引数に取得したDrawableを渡し、残りにはnullを指定しています。

補足:resources.getDrawable()はAPI 22以降で非推奨となっています。最新の環境では、以下のようにContextCompatを使用するのが推奨されます。

val img = ContextCompat.getDrawable(this, R.drawable.ic_baseline_alarm_24)

ステップ4:AndroidManifest.xml の確認

最後に、androidManifest.xml に以下のコードが正しく記述されていることを確認します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">

    <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」アイコンをクリックしてください。表示された候補の中から接続したモバイルデバイスを選択すると、端末上にアプリが起動し、ボタンのテキスト左側にアラームアイコンが表示された画面を確認できます。

  1. 【Android】ボタンのdrawableLeft(左側アイコン)をプログラムで動的に設定する方法

    はじめに このチュートリアルでは、Androidアプリのボタン(Button)に対して、テキストの左側に表示されるアイコン(drawableLeft / drawableStart)をプログラムから動的に設定する方法を解説します。 XMLレイアウトでは android:drawableStart 属性で静的に指定できますが、「ユーザーの操作に応じてアイコンを切り替えたい」「条件によって表示を変えたい」といったケースでは、Javaコードからの設定が必要になります。 手順1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選

  2. AndroidでTextViewのレイアウトの重み(weight)をプログラム的に設定する方法

    この記事では、AndroidアプリでTextViewのレイアウトパラメータ(レイアウトの重み)をプログラム的に設定する方法を、実際のサンプルコードとともに解説します。 手順1:新しいプロジェクトを作成する Android Studioを起動し、「File」→「New Project」を選択して、必要な項目を入力し新しいプロジェクトを作成します。 手順2:activity_main.xmlにコードを追加する res/layout/activity_main.xmlに以下のコードを追加します。 <RelativeLayout xmlns:android="https://s