I want to use a preference summary to show the preference's current value, so I want to update the summary whenever the preference is changed. The preference in question is a storage location, chosen interactively by the user via an intent, using Android's Storage Access Framework. I've been beating my head over this for hours, trying all sorts of things found in SO threads, but I just can't figure out what combination of setSummary
,findPreference
, onSharedPreferenceChanged
, onSharedPreferenceChangeListener
, invoked in which class, I need.
My code currently looks something like this:
const val REQUEST_TARGET_FOLDER = 4
class SettingsActivity : AppCompatActivity() {
private lateinit var prefs: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, SettingsFragment())
.commit()
}
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
// from: https://stackoverflow.com/questions/63575398/how-to-correctly-receive-and-store-a-local-directory-path-in-android-preferences
val targetDirPreference: Preference? = findPreference("export_dir")
targetDirPreference?.setOnPreferenceClickListener {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
activity?.startActivityForResult(intent, REQUEST_TARGET_FOLDER)
true
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
// from: https://stackoverflow.com/questions/34331956/trying-to-takepersistableuripermission-fails-for-custom-documentsprovider-via
if (requestCode == REQUEST_TARGET_FOLDER && resultCode == RESULT_OK && intent != null) {
val treeUri = intent.data
if (treeUri != null) {
// do stuff
}
with(prefs.edit()) {
putString("export_dir", intent.data.toString())
apply()
}
}
}
}
This is the preference involved:
<Preference
android:key="export_dir"
android:title="Export to directory:" />
Can someone please help me figure out what to do to set / update the preference's summary when the user selects a directory? (The directory selection part itself currently works.)