findPreference()返回null

时间:2019-10-17 16:36:10

标签: java android sharedpreferences preferences

我正在尝试实用地将SwitchPreferenceCompat的Toggle开关更改为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);

1 个答案:

答案 0 :(得分:0)

我正在使用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();
  

注意:我没有测试过该Java版本,但是概念是这样的。