|
18 | 18 | import androidx.annotation.PluralsRes; |
19 | 19 | import androidx.annotation.StringRes; |
20 | 20 | import androidx.appcompat.app.AppCompatDelegate; |
| 21 | +import androidx.core.content.ContextCompat; |
21 | 22 | import androidx.core.math.MathUtils; |
22 | 23 | import androidx.core.os.LocaleListCompat; |
23 | 24 | import androidx.preference.PreferenceManager; |
@@ -71,6 +72,46 @@ public final class Localization { |
71 | 72 |
|
72 | 73 | private Localization() { } |
73 | 74 |
|
| 75 | + /** |
| 76 | + * Gets a string like you would normally do with {@link Context#getString}, except that when |
| 77 | + * Context is not an AppCompatActivity the correct locale is still used. The latter step uses |
| 78 | + * {@link ContextCompat#getString}, which might fail if the Locale system service is not |
| 79 | + * available (e.g. inside of Compose previews). In that case this method falls back to plain old |
| 80 | + * {@link Context#getString}. |
| 81 | + * <p>This method also supports format args (see {@link #compatGetString(Context, int, |
| 82 | + * Object...)}, unlike {@link ContextCompat#getString}.</p> |
| 83 | + * |
| 84 | + * @param context any Android context, even the App context |
| 85 | + * @param resId the string resource to resolve |
| 86 | + * @return the resolved string |
| 87 | + */ |
| 88 | + public static String compatGetString(final Context context, @StringRes final int resId) { |
| 89 | + try { |
| 90 | + return ContextCompat.getString(context, resId); |
| 91 | + } catch (final Throwable e) { |
| 92 | + return context.getString(resId); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * @see #compatGetString(Context, int) |
| 98 | + * @param context any Android context, even the App context |
| 99 | + * @param resId the string resource to resolve |
| 100 | + * @param formatArgs the formatting arguments |
| 101 | + * @return the resolved string |
| 102 | + */ |
| 103 | + public static String compatGetString(final Context context, |
| 104 | + @StringRes final int resId, |
| 105 | + final Object... formatArgs) { |
| 106 | + try { |
| 107 | + // ContextCompat.getString() with formatArgs does not exist, so we just |
| 108 | + // replicate its source code but with formatArgs |
| 109 | + return ContextCompat.getContextForLanguage(context).getString(resId, formatArgs); |
| 110 | + } catch (final Throwable e) { |
| 111 | + return context.getString(resId, formatArgs); |
| 112 | + } |
| 113 | + } |
| 114 | + |
74 | 115 | @NonNull |
75 | 116 | public static String concatenateStrings(final String... strings) { |
76 | 117 | return concatenateStrings(DOT_SEPARATOR, Arrays.asList(strings)); |
|
0 commit comments