LoginSignup
4
0

More than 3 years have passed since last update.

xamarin-forms-tab-badgeでバッジ表示してみる(Xamarin, Android)

Last updated at Posted at 2020-12-07

はじめに

モバイルアプリケーションを開発するときに、Xamarinを採用することもあると思います。
Xamarinについての説明はここでは割愛し、xamarin-forms-tab-badgeを利用して、通知のバッジを表示することに関して記載します。
ライブラリのドキュメントに使い方があるのでそれで十分なのですが、日本語の情報があまり見当たらなかったので、何かの参考になれば嬉しいです。
(なお、Androidエミュレータでしか確認していないため、iOSでは未確認です。)

■ 参考
Xamarin:Xamarin(ザマリン) とはなんぞや
xamarin-forms-tab-badge:https://github.com/xabre/xamarin-forms-tab-badge

完成イメージ

image.png
通知タブに赤丸でバッジが表示される。
タブの位置やスタイルに関しての実装については割愛します。
参考:TabbedPage

実装

注:タブ機能の簡易な実装方法として、Xamarin.Forms Shellというものがありますが、こちらを利用するとバッジ表示ができないようなので、TabbedPageを利用します。

xamarin-forms-tab-badgeのインストール

VisualStudioのソリューションエクスプローラ上でプロジェクトを右クリック>NuGetパッケージ管理をクリック
plugin.png
Plugin.Badgeを検索し、[インストール]ボタンをクリック

AssemblyInfo.csを修正

[プロジェクト名].Android/Properties/AssemblyInfo.cs を開き、以下を追加

AssemblyInfo.cs
[assembly: ExportRenderer(typeof(TabbedPage), typeof(BadgedTabbedPageRenderer))]

必要に応じて、usingを追加

TabbedPageの実装

TabbedPageのサブクラスをMainTabPage(任意)として実装する。
バッジを付けたい項目に属性としてplugin:TabBadge.BadgeText="{Binding NotificationCount}"を追加

MainTabPage.xaml
    <NavigationPage Title="通知" 
                    IconImageSource="{FontImage FontFamily={StaticResource MaterialFontFamily}, Glyph={Static icons:MaterialIcon.Bell}, Size=50}"
                    plugin:TabBadge.BadgeText="{Binding NotificationCount}">
        <x:Arguments>
            <local:NotificationListPage />
        </x:Arguments>
    </NavigationPage>

コードビハインドにバッジを変更するメソッドを用意

MainTabPage.cs
    public partial class MainTabPage : TabbedPage
    {
        public MainTabPage()
        {
            InitializeComponent();
            BindingContext = new { NotificationCount = "" };
        }

        public void ChangeNotificationBadge(int count)
        {
            if (count == 0)
            {
                BindingContext = new { NotificationCount = "" };
            } else
            {
                BindingContext = new { NotificationCount = "" + count };
            }
        }
    }

バッジ表示の実装

今回はAppから通知をつける場合を実装する。
上で実装したバッジ変更のメソッドを呼び出す

App.cs
   if (Current.MainPage is MainTabPage tabPage)
   {
       tabPage.ChangeNotificationBadge(1);
   }

まとめ

Shellが使えず、自分でTabbedPageを実装しないといけないのは少し面倒ではありますが、ライブラリを利用すると簡単にバッジ表示機能が実装できました。
iOSの場合はLinkerの設定などあるらしいので、もう一手間必要そうです。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0