首页 > 解决方案 > How do I reference a preference option by key in my PreferenceScreen?

问题描述

I have a preference screen, and I want to disable visibility of a preference setting programaticaly in OnCreate depending of which version of android we are using. In order to do that I must be able to reference that particular preference object.

While I see a lot of examples using findPreference() I see that that method is deprecated and Android studio doesn't suggest any similar method.

I don't know how you reference a preference by key other than that.

Here is my activity:

class SettingsActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {

val Tag = "My Activity:"

companion object {
    private val TAG_TITLE = "PREFERENCE_ACTIVITY"
}

override fun onCreate(savedInstanceState: Bundle?) {
    val pManager = SharedPreferencesManager(this)
    pManager.loadTheme()
    super.onCreate(savedInstanceState)

    PreferenceManager.getDefaultSharedPreferences(this)
        .registerOnSharedPreferenceChangeListener(this)

    setContentView(R.layout.activity_settings)

    if (savedInstanceState == null) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.content_preference, MainPreference()).commit()
    } else {
        title = savedInstanceState.getCharSequence(TAG_TITLE)
    }

    supportFragmentManager.addOnBackStackChangedListener {
        if (supportFragmentManager.backStackEntryCount == 0) {
            setTitle("Settings")
        }
    }
    setUpToolbar()

}

override fun onDestroy() {
    super.onDestroy()
    PreferenceManager.getDefaultSharedPreferences(this)
        .unregisterOnSharedPreferenceChangeListener(this)

}

override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
    super.onSaveInstanceState(outState, outPersistentState)
    outState.putCharSequence(TAG_TITLE, title)
}

override fun onSupportNavigateUp(): Boolean {
    if (supportFragmentManager.popBackStackImmediate()) {
        return true
    }
    return super.onSupportNavigateUp()
}

private fun setUpToolbar() {
    supportActionBar?.setTitle("Settings")
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    supportActionBar?.setDisplayShowHomeEnabled(true)
}

class MainPreference : PreferenceFragmentCompat() {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.preferences, rootKey)
    }

}

override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
    recreate()
}

}

标签: androidkotlinkeypreferencepreferencescreen

解决方案


I think you might be referring to the non support library versions of the preferences API which are indeed going to be deprecated after API 29. However in PreferenceFragmentCompat, findPreference is still the approach you should be using.

You can have a look at the method documentation here: findPreference(CharSequence).


推荐阅读