如何在 kotlin 活动中获取列表首选项值



如何在活动中获取所选选项的列表首选项值?

法典

root_preferences.xml

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/settings_header">
<ListPreference
app:defaultValue="English"
app:entries="@array/reply_entries"
app:entryValues="@array/reply_values"
app:key="reply"
app:title="@string/select_language"
app:useSimpleSummaryProvider="true" />
</PreferenceCategory>
</PreferenceScreen>

arrays.xml

<resources>
<string-array name="reply_entries">
<item>English</item>
<item>Bahasa Indonesia</item>
<item>فارسی</item>
<item>العربی</item>
</string-array>
<string-array name="reply_values">
<item>en</item>
<item>in</item>
<item>fa</item>
<item>ar</item>
</string-array>
</resources>

SettingsActivity.kt

class SettingsActivity : BaseActivity() {
lateinit var langCode: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, SettingsFragment())
.commit()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
}
//
private fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
Log.e("My key:", key) // currently won't print anything
when (key) {
"reply" -> {
Toast.makeText(this, "Reply selected", Toast.LENGTH_SHORT).show()
}
"en" -> {
Toast.makeText(this, "en selected", Toast.LENGTH_SHORT).show()
}
"id" -> {
Toast.makeText(this, "id selected", Toast.LENGTH_SHORT).show()
}
"fa" -> {
Toast.makeText(this, "fa selected", Toast.LENGTH_SHORT).show()
}
"ar" -> {
Toast.makeText(this, "ar selected", Toast.LENGTH_SHORT).show()
}
}
}
After search 1 day, got solution.
1. 
<ListPreference
app:key="@string/keylist_preference"
app:title="@string/title_list_preference"
app:summary="%s"
app:entries="@array/entries"
app:entryValues="@array/entry_values"
app:dialogTitle="@string/dialog_title_list_preference"/>
2. <resources>
<string-array name="entries">
<item>SIT1-8143</item>
<item>SIT2-8243</item>
<item>SIT3-8343</item>
<item>SIT4-8443</item>
<item>SIT5-8543</item>
<item>SIT6-8643</item>
</string-array>
<string-array name="entry_values">
<item>https://172.29.226.197:8143</item>
<item>https://172.29.226.197:8243</item>
<item>https://172.29.226.197:8343</item>
<item>https://172.29.226.197:8443</item>
<item>https://172.29.226.197:8543</item>
<item>https://172.29.226.197:8643</item>
</string-array>

3. 
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.dialogs, rootKey)
val listPreference = findPreference<Preference>(getString(R.string.keylist_preference)) as ListPreference?
listPreference?.setOnPreferenceChangeListener { preference, newValue ->
if (preference is ListPreference) {
val index = preference.findIndexOfValue(newValue.toString())
val entry = preference.entries.get(index)
val entryvalue = preference.entryValues.get(index)
Log.i("selected val", " position - $index value - $entry, entryvalue - $entryvalue ")
}
true
}
}

更新:我使用DialogFragment设计了一个解决方案:

class LanguageListFragment : DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.select_language, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val radioGroup = view.findViewById<RadioGroup>(R.id.lang_radio_group)
radioGroup.setOnCheckedChangeListener { group, checkedId ->
when (checkedId) {
R.id.ar -> {
languageSaved("ar")
}
R.id.bh -> {
languageSaved("bh")
}
R.id.en -> {
languageSaved("en")
}
//add more if needed..
}
}
}
fun languageSaved(languageCode: String) {
val myPref: PrefManager = PrefManager(context!!)
myPref.language = languageCode
Toast.makeText(
activity, "Clicked: Bhasa", Toast.LENGTH_SHORT
).show()
// reset the activity
ActivityCompat.finishAffinity(activity!!)
startActivity(Intent(activity!!, MainActivity::class.java))
}
}

片段视图:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="@+id/lang_radio_group"
android:layout_width="161dp"
android:layout_height="118dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.184"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137">
<RadioButton
android:id="@+id/ar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Arabic" />
<RadioButton
android:id="@+id/bh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bhasa" />
<RadioButton
android:id="@+id/en"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="English" />
</RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>

使用此首选项管理器而不是以前的首选项管理器:

class PrefManager(private val mContext: Context) {
private var editor: SharedPreferences.Editor? = null
private var prefs: SharedPreferences? = null
private val LANGUAGE = "language"
private val PREF = "user_info"
var language: String?
get() {
this.prefs = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE)
return this.prefs!!.getString(LANGUAGE, "en")
}
set(language) {
this.editor = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit()
this.editor!!.putString(LANGUAGE, language)
this.editor!!.apply()
}
}

更新结束

您需要为SharedPref.设置正确的侦听器,因此我们将使用帮助程序方法来注册侦听器。 ,然后使用您希望在SharedPref.发生任何更改时调用回调的活动或片段进行注册。

设置正确的侦听器:(您也可以使用匿名侦听器。

import android.content.Context
import android.content.SharedPreferences
import android.util.Log
class PrefManager(private val mContext: Context) {
private var editor: SharedPreferences.Editor? = null
private var prefs: SharedPreferences? = null
private val LANGUAGE = "language"
private val PREF = "user_info"
var language: String?
get() {
return this.prefs!!.getString(LANGUAGE, "en")
}
set(language) {
this.editor = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit()
this.editor!!.putString(LANGUAGE, language)
this.editor!!.apply()
Log.d("TAG", "Should be saved")
}
fun regListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
this.prefs = this.mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE)
/*this.prefs!!.registerOnSharedPreferenceChangeListener { sharedPreferences: SharedPreferences, s: String ->
Log.d("TAG", "Listener Fired: $s")
}*/
this.prefs!!.registerOnSharedPreferenceChangeListener(listener)
}
}

现在,在需要值的位置注册您的活动:

class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onCreate(savedInstanceState: Bundle?) {
//        val wordViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myPref = PrefManager(this)
myPref.regListener(this)
myPref.language = "en"
myPref.language = "bn"
myPref.language = "ar"
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
val firedWithValue = sharedPreferences!!.getString(key, "default value")
Log.d("TAG", "Fired Pref. $firedWithValue")
}
}

现在,当我们this作为侦听器传递并实现OnSharedPreferenceChangeListener每次language值时都会调用我们的 acticvity 的OnSharedPreferenceChangeListener()方法set

最新更新