BottomNavigation BadgeDrawable set displayed number in a specific Locale irrespective of selected one

Viewed 439

The project supports RTL; Arabic in particular. The requirement is that all numbers must appear in English format even when language is selected as Arabic Locale, the way we achieve it everywhere is usually the following code in case of TextViews:

TextView t = findViewById(R.id.sampleTV);
t.setText(String.format("123",Locale.US));

Here 123 would be shown as "123" since we formatted it in US locale quite hardcoded-ly not "١٢٣"

I want to achieve the same for the Badge Notifications provided by Android Material Component's Bottom Navigation, here is what I've tried:

if(navigation!=null) {  
  NumberFormat nf = NumberFormat.getInstance(Locale.US);

  BadgeDrawable badgeDrawable = navigation.getOrCreateBadge(R.id.nav_account);
  if (badgeDrawable != null) {
      if((counterNoti + counter + counterRoom) <= 0) {
      badgeDrawable.setVisible(false);
      badgeDrawable.clearNumber();
  }
  else
      {
      int x = counterNoti + counter + counterRoom;
      nf.format(x);
      badgeDrawable.setVisible(true);
      badgeDrawable.setNumber(x);
  }
}

(where navigation is reference to my BottomNavigation!)

Yet even with this the number is shown in Arabic not like setText's case. Is there a way to achieve this or I need an alternative?

Appreciate your input and time! Thanks.

2 Answers

The following worked for me, changing the local for the current JVM instance by calling the following function in onCreate

private fun numbersFormat() {
    val locale = Locale.ENGLISH
    Locale.setDefault(locale)
}

You can't change badge numeric text locale in a simple way. My decision was to create custom badge via xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_badge"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/txt_counter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top|right"
    android:layout_marginTop="4dp"
    android:layout_marginRight="0dp"
    android:background="@drawable/bg_badge"
    android:gravity="center"
    android:minWidth="21dp"
    android:minHeight="21dp"
    android:textAppearance="@style/Typography.BadgeCounter"
    android:textColor="#ffffff"
    tools:ignore="RtlHardcoded"
    tools:text="999+" />

Inflate layout in your fragment and set TextView's text liek this:

txtCounter.text = NumberFormat.getInstance(Locale.ENGLISH).format(counter)
Related