Android how to detect/register language/locale change listener/receiver

The easy way is to register a BroadcastReceiver for Intent.ACTION_LOCALE_CHANGED.

Example: change your ViewModel data when language/locale changed.

public class QASViewModel extends ViewModel {
    @SuppressLint("StaticFieldLeak")
    private final FragmentActivity activity;

    public QASViewModel(@NonNull FragmentActivity activity) {
        this.activity = activity;
        setLangReceiver();
    }

    private void setLangReceiver() {
        final QASViewModel qasViewModel = this;
        final BroadcastReceiver langReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // do action when language change
            }
        };
        activity.getApplicationContext().registerReceiver(langReceiver,
                new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
    }
}

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)