[FIXED] How do I add a dark mode option in a ListView?

Issue

I have a ListView with the app’s more technical details and I want to implement a dark theme manual switch like this:
enter image description here

If it helps, here’s the OnClickListener I use:

aboutListView.setOnItemClickListener((parent, view, i, id) -> {
    if (i == 0) {
       ConnectivityManager connectivityManager1 = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo1 = connectivityManager1.getActiveNetworkInfo();
        if (networkInfo1 == null || !networkInfo1.isConnected() || !networkInfo1.isAvailable()) {
            Intent intent = new Intent(MainList.this, no_network.class);
            startActivity(intent);
            finish();

        } else {
            String url = "https://example.com/";
            CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder()
                    .setShareState(CustomTabsIntent.SHARE_STATE_OFF);
            CustomTabsIntent customTabsIntent = builder.build();
            customTabsIntent.launchUrl(this, Uri.parse(url));
        }

    } else if (i == 1) {
        ConnectivityManager connectivityManager1 = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo1 = connectivityManager1.getActiveNetworkInfo();
        if (networkInfo1 == null || !networkInfo1.isConnected() || !networkInfo1.isAvailable()) {
            Intent intent = new Intent(MainList.this, no_network.class);
            startActivity(intent);
            finish();
        } else {
            String url = "https://example.com/";
            CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder()
                    .setShareState(CustomTabsIntent.SHARE_STATE_OFF);
            CustomTabsIntent customTabsIntent = builder.build();
            customTabsIntent.launchUrl(this, Uri.parse(url));
        }
    }

});

Is there a simple way to do it?

Solution

For example, you can add MaterialAlertDialogBuilder when the user press on [Dark Theme]
and choose one from [ Day, DarkNight or System Default ]

And here is the code using AppCompatDelegate to control switching between different themes:

Light / Day:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

Night Mode:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

System Default:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)

Don’t forget which user choose.. for example to Shared Preference or any offline storage, to restore theme prefered to user when open app again.

Answered By – YasserElgammal

Answer Checked By – David Goodson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published