在 Android 中使用 RadioButton 启用夜间模式

Enable Night mode using RadioButton in Android

我的应用有 Dialogbox 和 3 RadiosRadioGroup,

所以如果勾选了Light Radio,点击确定后,应用的主题就会变成light theme
如果勾选Dark,点击确定后,主题会变成night theme
,如果勾选system,就会变成system.

工具栏:

<?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>

菜单:

<?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>

对话框:

<?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>

主要活动:

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

我尝试了我所知道的一切,而不是我不知道该怎么做。 谢谢关注!

我在您的代码中发现了一些要点。 首先,我认为你也必须从你的视图中找到你的单选按钮。 像这样:

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

第二,我认为您可以在调用 dialog.dimiss.

之前使用 SharedPreferences 来查找用户检查过的内容

下面将检查在 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;
            }
        }
    });

这就是我想要实现的目标

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

共享偏好:

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