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

Androidでカスタム通知レイアウトとテキストの色を作成する方法を徹底解説

このチュートリアルでは、Androidアプリにおいて標準的な通知と、RemoteViewsを使ったカスタム通知レイアウトの両方を作成する方法を、サンプルコード付きでわかりやすく解説します。カスタムレイアウトを活用すれば、通知のデザインやテキストの色などを自由にコントロールできるようになります。

全体の流れ

本記事の手順は以下の通りです。

  1. Android Studioで新規プロジェクトを作成する
  2. メイン画面のレイアウト(activity_main.xml)を用意する
  3. MainActivity.javaに通知の生成処理を実装する
  4. 通知・カスタム通知・通知内容表示用のレイアウトXMLを作成する
  5. AndroidManifest.xmlを設定する
  6. 実機またはエミュレータで動作を確認する

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

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

ステップ2:activity_main.xml の編集

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

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

ステップ3:MainActivity.java の実装

src/MainActivity.java に以下のコードを追加します。このサンプルでは2つのボタンを配置し、それぞれ次のメソッドを呼び出す構成になっています。

  • Notification():NotificationCompat.Builder を使った標準的な通知を表示します。
  • CustomNotification():RemoteViews でカスタムレイアウトを読み込み、独自デザインの通知を表示します。
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.os.Bundle;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notificationmain);
        Button bnotify = (Button) findViewById(R.id.notification);
        Button bcustomnotify = (Button) findViewById(R.id.customnotification);
        bnotify.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Notification();
            }
        });
        bcustomnotify.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                CustomNotification();
            }
        });
    }
    public void Notification() {
        // 通知のタイトルを設定
        String strtitle = getString(R.string.notificationtitle);
        String strtext = getString(R.string.notificationtext);
        Intent intent = new Intent(this, NotificationView.class);
        intent.putExtra("title", strtitle);
        intent.putExtra("text", strtext);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.logosmall)
            .setTicker(getString(R.string.notificationticker))
            .setContentTitle(getString(R.string.notificationtitle))
            .setContentText(getString(R.string.notificationtext))
            .addAction(R.drawable.ic_launcher, "Action Button", pIntent)
            .setContentIntent(pIntent) .setAutoCancel(true);
        NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationmanager.notify(0, builder.build());
    }
    public void CustomNotification() {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.customnotification);
        String strtitle = getString(R.string.customnotificationtitle);
        String strtext = getString(R.string.customnotificationtext);
        Intent intent = new Intent(this, NotificationView.class);
        intent.putExtra("title", strtitle);
        intent.putExtra("text", strtext);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.logosmall)
            .setTicker(getString(R.string.customnotificationticker))
            .setAutoCancel(true) .setContentIntent(pIntent)
            .setContent(remoteViews);
        remoteViews.setImageViewResource(R.id.imagenotileft,R.drawable.ic_launcher);
        remoteViews.setImageViewResource(R.id.imagenotiright,R.drawable.androidhappy);
        remoteViews.setTextViewText(R.id.title,getString(R.string.customnotificationtitle));
        remoteViews.setTextViewText(R.id.text,getString(R.string.customnotificationtext));
        // Notification Manager を生成
        NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Notification Manager で通知を構築して表示
        notificationmanager.notify(0, builder.build());
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

ステップ4:notificationmain.xml の作成

res/layout/notificationmain.xml に以下のコードを追加します。※コード内で R.layout.notificationmain を参照しているため、ファイル名は notificationmain.xml としてください。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Notification - 1" />
    <Button
        android:id="@+id/customnotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_below="@+id/notification"
        android:text="Custom Notification - 1" />
</RelativeLayout>

ステップ5:customnotification.xml の作成

カスタム通知のレイアウトを定義する res/layout/customnotification.xml に以下のコードを追加します。左側のアイコン、タイトル、本文テキスト、右側の画像を配置したシンプルな構成です。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imagenotileft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/imagenotileft" />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/imagenotileft" />
    <ImageView
        android:id="@+id/imagenotiright"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:padding="10dp" />
</RelativeLayout>

テキストの色を変更するには

カスタム通知内のテキストの色を変えたい場合は、対象の TextView に android:textColor 属性を追加する方法と、Java側で setTextColor() メソッドを呼び出す方法があります。

// XMLの場合:該当のTextViewに属性を追加
android:textColor="#FF5722"

// Javaの場合:RemoteViews経由で色を指定
remoteViews.setTextColor(R.id.title, Color.parseColor("#FF5722"));

ステップ6:notificationview.xml の作成

通知をタップした際に開く詳細画面のレイアウトとして、res/layout/notificationview.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/lbltitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbltitle" />
    <TextView
        android:id="@+id/lbltext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lbltitle"
        android:text="@string/lbltext" />
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/lbltitle" />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/lbltext" />
</RelativeLayout>

ステップ7:AndroidManifest.xml の設定

Manifests/AndroidManifest.xml に以下のコードを記述します。なお、通知タップ時に起動される NotificationView アクティビティも、忘れずにマニフェストへ登録しておいてください。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.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」アイコンをクリックします。デバイスを選択して実行すると、端末にデフォルト画面が表示されます。

画面上の「Notification」ボタンを押せば標準通知が、「Custom Notification」ボタンを押せばカスタムレイアウトを適用した通知が、それぞれステータスバーに表示されます。通知をタップすると、Intentで渡したタイトルとテキストが NotificationView 画面上に表示されることも確認してみてください。

Androidでカスタム通知レイアウトとテキストの色を作成する方法を徹底解説

  1. 【Android入門】カスタム評価バー(RatingBar)の作り方をステップ解説

    この記事では、Androidアプリでカスタム評価バー(RatingBar)を作成する方法を、実際に動作するサンプルコードとともに解説します。星の数・初期評価値・刻み幅はすべて自由に設定でき、ユーザーが選んだ評価をリアルタイムで取得できるシンプルなアプリを一緒に構築していきましょう。 ステップ1:新しいプロジェクトを作成する まずはAndroid Studioで新規プロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。 ステップ2:レイアウトファイル(activity_main.xml)を編集する res/la

  2. 【Android入門】テキストファイルを作成してデータを書き込む方法をわかりやすく解説

    このチュートリアルでは、Androidアプリでテキストファイルを作成し、そこにデータを書き込む方法を段階的に解説します。内部ストレージへのファイル保存は、ユーザーが入力したメモや設定値などを端末内に永続化したい場合に役立つ基本的なテクニックです。 手順1:新規プロジェクトを作成する まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。 手順2:レイアウトファイル(activity_main.xml)を編集する res/layout/activity_main.xml