fix(android/engine): Add help method to localize Toast notifications

This commit is contained in:
Darcy Wong 2021-03-04 14:57:58 +07:00
parent bdb4755ed9
commit 8a176dcb8f

View file

@ -9,6 +9,8 @@ import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.LocaleList;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
@ -18,6 +20,20 @@ import com.tavultesoft.kmea.util.ContextUtils;
import java.util.Locale;
public class BaseActivity extends AppCompatActivity {
static ContextWrapper localeUpdatedContext;
/**
* Some classes aren't an AppCompatActivity and need this helper to localize Toast notifications
* in the updated locale.
* @param defaultContext - the context to fallback if localeUpdatedContext is null
* @param resID - resource ID of the string
* @param duration - length of the Toast notification (Toast.LENGTH_LONG or Toast.LENGTH_SHORT)
*/
public static void makeToast(Context defaultContext, int resID, int duration) {
Context context = (localeUpdatedContext != null) ? localeUpdatedContext : defaultContext;
String msg = context.getString(resID);
Toast.makeText(context, msg, duration).show();
}
@Override
protected void attachBaseContext(Context newBase) {
@ -36,7 +52,7 @@ public class BaseActivity extends AppCompatActivity {
} else {
localeToSwitchTo = Locale.forLanguageTag(languageTag);
}
ContextWrapper localeUpdatedContext = ContextUtils.updateLocale(newBase, localeToSwitchTo);
this.localeUpdatedContext = ContextUtils.updateLocale(newBase, localeToSwitchTo);
super.attachBaseContext(localeUpdatedContext);
}