ステータスバーのアイコン/通知ウインドウのテキストを動的に切り替える方法
いくつかのアプリを使っていると、ステータスバーのアイコンが動的に切り替わっているものがありました。どのように実装しているのでしょう?私も作ってみました。
概要
こんな画面イメージのものを作りました。まずは、ノーティフィケーション初期表示時のイメージです。星型のアイコンが表示されています。
通知ウインドウを表示したところです。タイトルと概要の末尾の数字は、動的に変更させています。
作業の流れ
- 複数の画像を用意する
- 上記画像をまとめるXMLを作成する
- ノーティフィケーションを表示する
- 上記で作成したノーティフィケーションを適宜切り替える
XML
プロジェクトの/res/drawableに任意の名前で、下記のようなXMLファイルを作成しました。ここでは、level_list.xmlというファイル名にしました。
※maxLevelには整数値のみ設定できるようです。
<?xml version="1.0" encoding="utf-8"?> <level-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:maxLevel="0" android:drawable="@drawable/star_big_on" /> <item android:maxLevel="1" android:drawable="@drawable/creep001" /> <item android:maxLevel="2" android:drawable="@drawable/creep002" /> <item android:maxLevel="3" android:drawable="@drawable/creep003" /> <item android:maxLevel="4" android:drawable="@drawable/creep004" /> <item android:maxLevel="5" android:drawable="@drawable/creep005" /> <item android:maxLevel="6" android:drawable="@drawable/creep006" /> <item android:maxLevel="7" android:drawable="@drawable/creep007" /> <item android:maxLevel="8" android:drawable="@drawable/creep008" /> </level-list>
ノーティフィケーション作成・表示
ノーティフィケーションを作成し、表示します。ポイントは、次です。
- Notificationオブジェクト作成時に渡すアイコンとして、上述したXML(R.drawable.level_list)を指定する。
- NotificationManager#notify()呼び出し時のノーティフィケーションIDは後で使えるように保持している。
// 通知ウインドウをクリックした際に起動するインテント Intent intent = new Intent(this, this.getClass()); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); // ステータスバー通知の設定 notification = new Notification(R.drawable.level_list, "Notificationテストです", System.currentTimeMillis()); notification.iconLevel = 0; // 通知ウインドウのメッセージ notification.setLatestEventInfo(this, "NotificationActivity", "Notificationテスト", pendingIntent); // ノーティフィケーション通知 ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(notificationId, notification);
ノーティフィケーション切り替え
先ほどと同様に、NotificationManager#notify()を呼び出して、通知を行います。ポイントは次です。
- Notification#iconLevelに、上述XMLのmaxLevelの値を動的に設定する。下記の例では、増減が1つずつですが、もちろん色々な値を設定可能です。XMLのmaxLevelの最大値よりも大きな値を設定すると、アイコンが表示されなくなります。マイナス値を設定しても表示されなくなります。
- NotificationManager#notify()に渡すノーティフィケーションIDは、前回と同じ。
notification.iconLevel++;
notification.iconLevel--;
notification.setLatestEventInfo(this, "NotificationActivity " + notification.iconLevel, "Notificationテスト " + notification.iconLevel, notification.contentIntent); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(notificationId, notification);