首页 > 解决方案 > 我无法使暗/亮模式切换正常工作

问题描述

我试图实现一个暗/亮模式开关,它使用共享首选项文件保存开关的状态。我希望用户能够从设置片段中更改应用程序的外观。但是,当我在关闭模拟器后打开应用程序时,在它保持轻量模式之前没有关闭应用程序,如果我打开设置片段,它会重新启动我的应用程序。我是使用片段和共享首选项文件的新手,因此欢迎任何有关如何使其正常工作的建议!

Setting Fragment XML:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SettingsFragment">

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:id="@+id/textView6"
        android:layout_width="113dp"
        android:layout_height="49dp"
        android:layout_gravity="top"
        android:layout_marginStart="131dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="137dp"
        android:text="@string/settings"
        android:textSize="28sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/tvDarkSide"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvDarkSide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:text="@string/light_dark_mode"
        android:textColor="#F10000"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="@+id/switchMode"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/switchMode" />

    <Switch
        android:id="@+id/switchMode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="110dp"
        android:layout_marginEnd="23dp"
        android:text="Switch"
        android:textSize="18sp"
        android:checked="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

SettingsFragment class:
public class SettingsFragment extends Fragment {


    public SettingsFragment() {
        // Required empty public constructor
    }

    public static final String SAVE_SWITCH = "saveSwitch";
    public static final String IS_CHECKED = "isChecked";

    //Citire din fis SharedPreferences
    private void loadFromSharedPreferences(SharedPreferences shP, Switch sw){
        boolean ischecked = shP.getBoolean(IS_CHECKED, false);
        sw.setChecked(ischecked);
        ((MainActivity) getActivity()).ToggleTheme(ischecked);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_settings, container, false);

        final Switch switchTheme = (Switch) view.findViewById(R.id.switchMode);
        final SharedPreferences sharedPreferences = getActivity().getApplicationContext()
                .getSharedPreferences( SAVE_SWITCH , Context.MODE_PRIVATE);

        loadFromSharedPreferences(sharedPreferences, switchTheme);

        switchTheme.setChecked(sharedPreferences.getBoolean(IS_CHECKED,false));

        switchTheme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {


            SharedPreferences.Editor editor = sharedPreferences.edit();

            //Scriere in fis SharedPreferences
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    editor.putBoolean(IS_CHECKED,true);
                    switchTheme.setChecked(true);
                    editor.apply();
                    ((MainActivity) getActivity()).ToggleTheme(isChecked);
                }
                else{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    editor.putBoolean(IS_CHECKED, false);
                    switchTheme.setChecked(false);
                    editor.apply();
                    ((MainActivity) getActivity()).ToggleTheme(isChecked);
                }
            }
        });
        return view;
    }
}

MainActivity class:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
            setTheme(R.style.AppThemeDark);
        } else {
            setTheme(R.style.AppTheme);
        }
        setContentView(R.layout.activity_main);

        final DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
        findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view){
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });


        NavigationView navigationView = findViewById(R.id.navigationView);
        navigationView.setItemIconTintList(null);

        NavController navController = Navigation.findNavController(this, R.id.navHostFragment);
        NavigationUI.setupWithNavController(navigationView, navController);

        final TextView textTitle = findViewById(R.id.textTitle);

        navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                textTitle.setText(destination.getLabel());
            }
        });
    }

    public void ToggleTheme( boolean isChecked ){
        if (isChecked) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

        }
        else{
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }

        finish();
      startActivity(new Intent(MainActivity.this, MainActivity.this.getClass()));
        //recreate();
    }
}

标签: javaandroidandroid-fragments

解决方案


推荐阅读