我从 Android Studio 进行了设置活动,而不是手动进行。我想做一个在应用程序中应用暗模式的开关。问题是,当我单击开关时,没有移动动画,只有应用程序闪烁。当我返回主活动时,我看到主题已应用(我之前只尝试过主活动),但是当我尝试返回设置时,一切都被冻结了!什么都不能点击,完全没有反应。这是我的 Java 代码:
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:
<PreferenceScreen
xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory
app:title="General">
<SwitchPreference
app:key="darkmode"
app:title="Dark mode"/>
</PreferenceCategory>
这是应用主题后的Logcat:
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中尝试暗模式时,有两行,在我的设置活动中无法放置,因为类是静态的.. 。 请帮忙!
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()));
}
});