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

【Android開発入門】チェックボックスの色を変更する方法をわかりやすく解説

Androidアプリでチェックボックス(CheckBox)を使う際、デフォルトの色のままだとデザインに馴染まないことがあります。この記事では、ボタンのクリック操作でチェックボックスの文字色と背景色を動的に変更する方法を、サンプルコード付きでステップごとに解説します。

実装のポイント

チェックボックスの色を変更するには、以下のメソッドを使用します。

  • setTextColor() … テキスト(ラベル)の色を変更する
  • setBackgroundColor() … 背景色を変更する

手順1:Android Studioで新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な情報を入力して新しいプロジェクトを作成します。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。TextView・CheckBox・Buttonを配置したシンプルなレイアウトです。

<?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:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click the check box" />

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check box"
        android:layout_below="@id/tv"
        android:paddingRight="15dp"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Color"
        android:layout_below="@id/checkbox" />

</RelativeLayout>

手順3:MainActivity.javaに色変更処理を実装する

src/MainActivity.java に以下のコードを記述します。ボタンがクリックされると、setTextColor(Color.RED) でテキストを赤色に、setBackgroundColor(Color.parseColor("#cbff75")) で背景を薄い緑色に変更します。

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox);
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // テキスト色を赤に変更
                checkBox.setTextColor(Color.RED);
                // 背景色をカラーコードで指定
                checkBox.setBackgroundColor(Color.parseColor("#cbff75"));
            }
        });
    }
}

なお、Color.parseColor() を使うと、"#cbff75" のような16進数のカラーコードを直接指定できるため、細かい色調整に便利です。

手順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」アイコンをクリックしてください。接続した端末を選択すると、スマートフォンの画面にアプリが表示されます。

初期画面ではチェックボックスは通常のスタイルで表示されています。

【Android開発入門】チェックボックスの色を変更する方法をわかりやすく解説

「Change Color」ボタンをタップすると、チェックボックスのテキストが赤色になり、背景色も変化します。

【Android開発入門】チェックボックスの色を変更する方法をわかりやすく解説

補足:より現代的な色指定方法

上記の方法はJavaコードから動的に色を変更する手法です。レイアウトXMLだけで静的に設定したい場合は、AppCompatライブラリやMaterial Componentsを使用して、app:buttonTint 属性でチェックマーク部分の色を指定したり、テーマの colorAccent(Material 3では colorPrimary)を変更したりする方法もあります。用途に応じて使い分けると良いでしょう。

  1. Androidのオプションメニューの背景色を変更する方法を徹底解説

    Androidのオプションメニューの背景色を変更する方法この記事では、Androidアプリのオプションメニュー(オプションズメニュー)の背景色を変更する方法を、実際に動作するサンプルコードとともにステップごとに解説します。テーマ(styles.xml)にandroid:itemBackgroundを設定するだけで、メニューの背景色を簡単にカスタマイズできます。ステップ1:新規プロジェクトの作成まず、Android Studioで新しいプロジェクトを作成します。メニューからFile → New Projectを選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。ステップ2:レイアウト

  2. 【Android開発】システムバージョン(OSバージョン・APIレベル)を確認・表示する方法

    Androidのシステムバージョンをプログラムで確認する方法 この記事では、Androidアプリ内で端末のシステムバージョン(OSバージョン・コードネーム・APIレベル)を取得し、画面に表示する方法を、実際のコード例とともにステップごとに解説します。バージョンによって処理を分岐させたい場合などに役立つテクニックです。 手順1:Android Studioで新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目(プロジェクト名、パッケージ名、保存先など)を入力して、新しいプロジェクトを作成してください。