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));
    }
}

No comments:

Post a Comment

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...