gpt4 book ai didi

java - findPreference() 返回 null

转载 作者:行者123 更新时间:2023-12-01 22:56:38 29 4
gpt4 key购买 nike

我正在尝试实用地将 SwitchPreferenceCompat 的切换开关更改为 true 和 false。但是,在 SettingsFragment 类中,方法 ammendSwitchPreferenceSetting() 首选项变量始终为 null,但是如果我从 onCreatePreferences() 中调用此方法,它将起作用,但我需要在其他地方调用它。


import android.os.Bundle;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.CheckBoxPreference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;

public class SettingsActivity extends AppCompatActivity {

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

//will allow the user to go back to parent page of the application
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);
}

public void ammendSwitchPreferenceSetting(String key, boolean value){
//is always null for some reason
SwitchPreferenceCompat preference = findPreference(key);
preference.setChecked(value);
}

}
}
 <SwitchPreferenceCompat
android:enabled="true"
android:summary="some summary"
app:defaultValue="true"
app:key="NetworkType"
app:title="some title" />

然后我从另一个类调用它

SettingsActivity.SettingsFragment settingsFragment = new SettingsActivity.SettingsFragment();
settingsFragment.ammendSwitchPreferenceSetting("NetworkType", false);

最佳答案

我正在使用 Kotlin,这就是我更改开关值的方法。

val sharedpref = PreferenceManager.getDefaultSharedPreferences(this).edit()
sharedpref.putBoolean("NetworkType",false).apply()

在java中,会是这样的

sharedpref prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedpref.Editor editor = prefs.edit();
editor.putBoolean("NetworkType",false);
editor.apply();

Note: I didn't teste this Java version, but the concept is like that.

关于java - findPreference() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58437192/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com