在设置Android Studio中进行PreferenceSwitch后,应用程序冻结 [英] App freezes after PreferenceSwitch in settings Android Studio

查看:159
本文介绍了在设置Android Studio中进行PreferenceSwitch后,应用程序冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过Android Studio进行了设置活动,而不是手动进行.我想进行一个在应用程序中应用暗模式的开关.问题是,当我单击开关时,没有动画可移动,而应用程序只眨了眨眼.当我回到我的主要活动时,我看到应用了主题(我之前只在主要活动中尝试过),但是当我尝试返回设置时,一切都冻结了!什么都没有点击,根本没有反应. 这是我的Java代码:

I made settings activity from Android Studio, not manually. I want to make a switch that applies a dark mode in the app. The problem is that when I click the switch there is no animation for movement, only a blink from the app. When I go back in my Main Activity I see that the theme is applied(I have tried earlier only with the main activity), but when I try to go back in the settings everything is frozen! Nothing can be clicked, no reaction at all. This is my Java code:

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreference;

public class SettingsActivity extends AppCompatActivity {
    private SwitchPreference darkModeSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);

        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);
            SwitchPreference darkModeSwitch = (SwitchPreference) findPreference("darkmode");
            assert darkModeSwitch != null;
            darkModeSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    } else {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    }
                    return false;
                }
            });
        }
    }
}

这是root_preferences.xml:

This is root_preferences.xml:

<PreferenceScreen
xmlns:app="http://schemas.android.com/apk/res-auto">

<PreferenceCategory
    app:title="General">

    <SwitchPreference
        app:key="darkmode"
        app:title="Dark mode"/>
</PreferenceCategory>

这是应用主题后的Logcat:

And this is the Logcat after applying the theme:

avc: denied { getattr } for path="/proc/1" dev="proc" ino=3924 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:r:init:s0 tclass=dir permissive=0

我认为这可能是因为在应用主题之后我没有再次启动活动,因为当我在main_activity中尝试暗模式时,有两行内容无法放置在我的设置活动中,因为该类是静态...请帮忙!

I think that it may be because I have not started the activity again after applying the theme, because when I tried the dark mode in main_activity, there were two lines, which in my settings activity cannot be placed, because the class is static... Please help!

public void onClick(View v) {
                if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                } else {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                }
//These two
            finish();
            startActivity(new Intent(MainActivity.this, MainActivity.this.getClass()));
        }
    });

推荐答案

将其放入您的preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
    <SwitchPreferenceCompat
        app:defaultValue="false"
        app:key="@string/key_night_mode"
        app:summaryOff="@string/summary_night_mode_off"
        app:summaryOn="@string/summary_night_mode_on"
        app:title="@string/title_night_mode" />
</PreferenceScreen>

然后在SettingsFragment.java中将PreferenceFragmentCompat扩展到onCreatePreference()方法内:

Then in your SettingsFragment.java which extended PreferenceFragmentCompat inside the onCreatePreference() method:

    SwitchPreferenceCompat switchPreferenceCompat = findPreference(getString(R.string.key_night_mode));

    switchPreferenceCompat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    boolean isChecked = false;
                    if (newValue instanceof Boolean)
                        isChecked = (Boolean) newValue;
                    if (isChecked) {
                    //these lines so that the preference persists
getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_night_mode), true).apply();
                    //you do not need to finish and recreate activity
                    //it takes care of any such things that needs to be done  
                    //automatically
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    } else {
                        getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_night_mode), false).apply();
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    }
                    return true;
                }
            });

这些代码行对我有用.

注意:

    如果要依赖平台作为夜间主题,则
  1. AppTheme应该从Theme.AppCompat.DayNightTheme.MaterialComponents.DayNight扩展.否则,您可以创建分别从Theme.MaterialComponents.LightTheme.MaterialComponents扩展的单独的DayNight主题(AppCompat也具有相似的主题集).
  2. 每次启动应用程序时,它都需要尊重用户的偏好,并相应地以用户设置的主题启动.为此,您可以按照以下步骤检查首选项并在MyApplication类中设置主题:

  1. AppTheme should extends from Theme.AppCompat.DayNight or Theme.MaterialComponents.DayNight if you want to be dependent on platform for your night theme. Otherwise, you can create your separate Day and Night theme which extends from Theme.MaterialComponents.Light and Theme.MaterialComponents respectively(AppCompat has similar set of themes too).
  2. Every time the app starts, it needs to respect the user's preferences and start in the user setted theme accordingly. To achieve this, you can check the preference and set theme in the MyApplication class as follows:

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean nightMode = sharedPreferences.getBoolean(getString(R.string.key_night_mode), false);
    if (nightMode)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    else {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P)
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
        else
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
    }

这篇关于在设置Android Studio中进行PreferenceSwitch后,应用程序冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆