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

【Android】通知にEditTextを組み込むカスタム通知の作成方法を徹底解説

このチュートリアルでは、Androidの通知(Notification)内にEditText(テキスト入力欄)を組み込んだカスタム通知を作成する方法を解説します。通常の通知はテキストや画像の表示のみですが、RemoteViewsを使用することで、独自のレイアウトを持つ通知を実装できます。

全体の手順の流れ

  1. Android Studioで新規プロジェクトを作成
  2. メイン画面のレイアウト(activity_main.xml)を作成
  3. 通知用のカスタムレイアウト(custom_notification_layout.xml)を作成
  4. 通知生成処理をMainActivity.javaに実装
  5. AndroidManifest.xmlの設定を確認

ステップ1:Android Studioで新規プロジェクトを作成する

Android Studioを起動し、メニューから File → New Project を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。テンプレートは「Empty Activity」で問題ありません。

ステップ2:activity_main.xml にコードを追加する

まず、アプリのメイン画面に「Create notification(通知を作成)」ボタンを配置します。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">

    <Button
        android:onClick="createNotification"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:text="Create notification" />

</RelativeLayout>

ポイントは android:onClick="createNotification" の指定です。これにより、ボタンがタップされたときにMainActivity内の createNotification メソッドが自動的に呼び出されます。

ステップ3:カスタム通知レイアウト custom_notification_layout.xml を作成する

次に、通知本体に表示する独自レイアウトを作成します。res/layout/custom_notification_layout.xml という新しいファイルを作成し、以下のコードを記述してください。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="96dp"
    android:padding="10dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentStart="true"
        android:layout_marginEnd="10dp"
        android:contentDescription="@string/app_name"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/image"
        android:text="Testing"
        android:textColor="#000"
        android:textSize="18sp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_marginTop="8dp"
        android:layout_toEndOf="@+id/image"
        android:hint="Enter something..."
        android:inputType="text"
        android:textSize="14sp" />

</RelativeLayout>

このレイアウトでは、左側にImageView(アプリアイコン)、その右側にTextView(タイトル)、さらにその下にEditTextを縦方向に並べています。高さを96dpに固定している点に注目してください。通知ビューの高さには制限があるためです。

ステップ4:MainActivity.java に通知生成処理を実装する

続いて、実際にカスタム通知を生成するJavaコードを記述します。src/MainActivity.java に以下のように実装します。

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RemoteViews;

public class MainActivity extends AppCompatActivity {

    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

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

    public void createNotification(View view) {
        // カスタムレイアウトをRemoteViewsとして読み込む
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);

        mBuilder.setContent(contentView);
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);

        // Android 8.0(API 26)以降は通知チャンネルが必要
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    "NOTIFICATION_CHANNEL_NAME",
                    importance
            );
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

実装のポイント

  • RemoteViews:通知のような別プロセス上に表示されるUIに対しては、通常のViewではなくRemoteViewsを使ってカスタムレイアウトを適用します。
  • setAutoCancel(true):ユーザーが通知をタップすると自動的に通知が消えるようになります。
  • 通知チャンネル対応:Android 8.0(Oreo)以降では、通知チャンネルの作成が必須のため、SDK_INTの判定を行っています。

ステップ5:AndroidManifest.xml を確認・編集する

最後に、マニフェストファイルの設定を確認します。AndroidManifest.xml に以下のコードを記述します。

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

    <uses-permission android:name="android.permission.VIBRATE" />

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

ここではバイブレーション権限(VIBRATE)を宣言しています。通知時に振動させたい場合に必要となるパーミッションです。

アプリを実行して動作を確認しよう

それでは、作成したアプリケーションを実際に動かしてみましょう。実機のAndroid端末をPCに接続しておいてください。Android Studioでアクティビティファイルを開き、ツールバーのRun(実行)アイコンをクリックします。デバイス選択ダイアログで自分のスマートフォンを選択すると、端末側にアプリが起動します。

画面中央の「Create notification」ボタンをタップすると、ステータスバーにカスタム通知が表示され、通知を展開するとEditText付きのカスタムレイアウトが確認できます。

【Android】通知にEditTextを組み込むカスタム通知の作成方法を徹底解説

まとめ

本記事では、RemoteViewsを活用して通知内にEditTextを表示するカスタム通知の作成方法を紹介しました。カスタム通知を使いこなせば、再生コントロール付きの音楽プレイヤー通知や、進捗状況を表示する通知など、よりリッチなUIを提供できるようになります。ぜひ応用してみてください。

  1. FacebookでAndroidアプリを作成する方法|開発者サイトでの設定手順を徹底解説

    この記事では、FacebookでAndroidアプリを作成する方法について詳しく解説します。AndroidアプリとFacebookを連携させるには、Facebook開発者サイトでFacebookアプリを作成し、Facebook App IDを取得する必要があります。以下の手順に従って、順番に進めていきましょう。 準備:Facebook開発者サイトで新しいアプリを追加する まず、https://developers.facebook.com/ にアクセスし、「新しいアプリを追加」をクリックしてアプリの作成を開始します。 ステップ1:アプリ名とメールアドレスを入力する 指定されたフィールドに、作

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

    このチュートリアルでは、Androidアプリにおいて標準的な通知と、RemoteViewsを使ったカスタム通知レイアウトの両方を作成する方法を、サンプルコード付きでわかりやすく解説します。カスタムレイアウトを活用すれば、通知のデザインやテキストの色などを自由にコントロールできるようになります。 全体の流れ 本記事の手順は以下の通りです。 Android Studioで新規プロジェクトを作成する メイン画面のレイアウト(activity_main.xml)を用意する MainActivity.javaに通知の生成処理を実装する 通知・カスタム通知・通知内容表示用のレイアウトXMLを作成する A