How to handle mixed RTL & LTR languages in notifications?

偶尔善良 提交于 2019-12-03 12:22:41

OK, found an answer, based on this, this and this.

For the above case:

%1$s called %2$s

In order to change it correctly to Hebrew, you need to add the special character "\u200f" , as such:

  <string name="notification">%1$s התקשר ל %2$s</string>


    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (VERSION.SDK_INT >= VERSION_CODES.O) {
        String id = "my_channel_01";
        CharSequence name = "channelName";// getString(R.string.channel_name);
        String description = "channelDesc";//getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel channel = new NotificationChannel(id, name, importance);
        channel.setDescription(description);
        channel.enableLights(true);
        channel.setLightColor(Color.RED);
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        notificationManager.createNotificationChannel(channel);
    }
    Intent resultIntent = new Intent(this, MainActivity.class);
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    this,
                    0,
                    resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

    String[] names1 = new String[]{"משה", "Moses"};
    String[] names2 = new String[]{"דוד", "David"};
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 2; ++j) {
            String name1, name2;
            name1 = names1[i];
            name2 = names2[j];
            name1 = "\u200f" + name1 + "\u200f";
            name2 = "\u200f" + name2 + "\u200f";

            final String text = getString(R.string.notification, name1, name2);
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this, "TEST")
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(text)
                            .setContentIntent(resultPendingIntent)
                            .setChannelId("my_channel_01")
                            .setContentText(text);
            int notificationId = i*2+j;
            notificationManager.notify(notificationId, mBuilder.build());
        }
    }
}

You can also check if the current locale is RTL, before choosing to use this solution. Example:

public static boolean isRTL() {
    return
            Character.getDirectionality(Locale.getDefault().getDisplayName().charAt(0)) ==
                    Character.DIRECTIONALITY_RIGHT_TO_LEFT;
}

The result:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!