Enable Night mode using RadioButton in Android

1.1k views Asked by At

I have an app which has Dialogbox with 3 Radios and RadioGroup,
enter image description here

So if the Light Radio is checked, after clicking Okay, the theme of the app will be changed to light theme.
If Dark is checked, after clicking Okay, the theme will be changed to night theme
and if system it will be changed to system.

Toolbar:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFF"
    style="@style/TextAppearance.AppCompat.Widget.Button.Borderless.Colored"
    android:elevation="0dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

</androidx.appcompat.widget.Toolbar>

Menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/chooseTheme"
        android:onClick="chooseTheme"
        android:title="Choose Theme"
        app:showAsAction="never"
        tools:ignore="HardcodedText" />
</menu>

DialogBox:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <RadioGroup
        android:id="@+id/themeGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="5dp"
        android:gravity="center"
        android:paddingStart="20dp"
        android:paddingTop="20dp"
        android:paddingEnd="20dp"
        android:paddingBottom="5dp"
        tools:ignore="UselessParent">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:layout_marginBottom="20dp"
            android:text="Choose Theme"
            android:textColor="@color/black"
            android:textColorHint="#FFFFFF"
            android:textSize="20sp"
            tools:ignore="HardcodedText" />

        <RadioButton
            android:id="@+id/radioLight"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:layout_marginBottom="10dp"
            android:buttonTint="@color/colorPrimary"
            android:checked="true"
            android:text="Light"
            android:textSize="18sp"
            tools:ignore="HardcodedText" />

        <RadioButton
            android:id="@+id/radioDark"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:layout_marginBottom="10dp"
            android:buttonTint="@color/colorPrimary"
            android:text="Dark"
            android:textSize="18sp"
            tools:ignore="HardcodedText" />

        <RadioButton
            android:id="@+id/radioSystem"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:layout_marginBottom="10dp"
            android:buttonTint="@color/colorPrimary"
            android:text="System"
            android:textSize="18sp"
            tools:ignore="HardcodedText" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:layout_marginStart="80dp"
            android:orientation="horizontal"
            tools:ignore="RtlHardcoded">

            <Button
                android:id="@+id/btn_cancel"
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="100dp"
                android:layout_height="60dp"
                android:gravity="center|center_vertical|fill_vertical"
                android:scaleY="0.9"
                android:text="Cancel"
                android:textAlignment="center"
                android:textAllCaps="false"
                android:textColor="@color/colorPrimary"
                android:textSize="14sp"
                tools:ignore="ButtonStyle,HardcodedText" />

            <Button
                android:id="@+id/btn_okay"
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="100dp"
                android:layout_height="60dp"
                android:layout_marginStart="10dp"
                android:gravity="center|center_vertical|fill_vertical"
                android:scaleY="0.9"
                android:text="Okay"
                android:textAlignment="center"
                android:textAllCaps="false"
                android:textColor="@color/colorPrimary"
                android:textSize="14sp"
                tools:ignore="ButtonStyle,HardcodedText" />
        </LinearLayout>

    </RadioGroup>

</LinearLayout>

MainActivity:

public void chooseTheme(MenuItem item) {
        final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        View mView = getLayoutInflater().inflate(R.layout.dialog_theme,null);
        Button btn_cancel = mView.findViewById(R.id.btn_cancel);
        Button btn_okay = mView.findViewById(R.id.btn_okay);
        alert.setView(mView);
        final AlertDialog alertDialog = alert.create();
        alertDialog.setCanceledOnTouchOutside(false);

        RadioButton radioLight = findViewById(R.id.radioLight);
        final RadioButton radioDark =findViewById(R.id.radioDark);
        RadioButton radioSystem =findViewById(R.id.radioSystem);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        btn_okay.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

I tried everything I knew, not I have no idea how to do it. Thank you for attention!

3

There are 3 answers

9
private static On BEST ANSWER

The following will check which radio button is checked inside RadioGroup:

RadioGroup radioGroup = mView.findViewById(R.id.themeGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch(i) {
                case R.id.radioLight:
                     setLightTheme();
                    Toast.makeText(getApplicationContext(),"Light mode",Toast.LENGTH_LONG).show();
                    break;
                case R.id.radioDark:
                     setDarkTheme();
                    Toast.makeText(getApplicationContext(),"Dark mode",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    });

enter image description here

0
Hexley21 On

That's what was I trying to achieve

Boolean night = false;
    public void chooseTheme(MenuItem item) {
        final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        final View mView = getLayoutInflater().inflate(R.layout.dialog_theme,null);
        Button btn_okay = mView.findViewById(R.id.btn_okay);
        Button btn_cancel = mView.findViewById(R.id.btn_cancel);
        alert.setView(mView);
        final AlertDialog alertDialog = alert.create();
        alertDialog.setCanceledOnTouchOutside(false);
        final RadioGroup themeGroup = mView.findViewById(R.id.themeGroup);
        themeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onCheckedChanged(RadioGroup themeGroup, int i) {
                switch(i) {
                    case R.id.radioLight:
                        night = false;
                        break;
                    case R.id.radioDark:
                        night = true;
                        break;
                }
            }
        });
        btn_okay.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                if(night){
                    sharedpref.setNightModeState(true);
                    Toast.makeText(getApplicationContext(),"Dark mode", Toast.LENGTH_LONG).show();
                }
                else if (!night){
                    sharedpref.setNightModeState(false);
                    Toast.makeText(getApplicationContext(),"Light mode",Toast.LENGTH_LONG).show();
                }
                alertDialog.dismiss();
                restartApp();
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
                                    });
        alertDialog.show();
    }

SharedPref:

public class SharedPref {
    SharedPreferences mySharedPref ;
    public SharedPref(Context context) {
        mySharedPref = context.getSharedPreferences("filename",Context.MODE_PRIVATE);
    }
    // this method will save the nightMode State : True or False
    public void setNightModeState(Boolean state) {
        SharedPreferences.Editor editor = mySharedPref.edit();
        editor.putBoolean("NightMode",state);
        editor.apply();
    }
    // this method will load the Night Mode State
    public Boolean loadNightModeState (){
        Boolean state = mySharedPref.getBoolean("NightMode",false);
        return  state;
    }
}
0
sepehr narimani On

I found some points in your code. for first, I think you have to find your radio buttons from your view too. like this:

 RadioButton radioLight = mView.findViewById(R.id.radioLight);
 final RadioButton radioDark = mView.findViewById(R.id.radioDark);
 RadioButton radioSystem = mView.findViewById(R.id.radioSystem);

And for the second I think you can use SharedPreferences to find what the user has checked, before calling dialog.dimiss.