代码之家  ›  专栏  ›  技术社区  ›  mafortis

如何在kotlin活动中获取ListPreference值

  •  0
  • mafortis  · 技术社区  · 5 年前

    我如何在活动中获取所选选项的ListPreference值?

    代码

    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()
                }
            }
        }
    
    0 回复  |  直到 5 年前
        1
  •  4
  •   siddhartha shankar    4 年前
    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
                }
            }
    
        2
  •  1
  •   some user    5 年前

    更新: 我设计了一个解决方案 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>
    

    使用此PrefManager而不是之前的PrefManager:

    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. 因此,我们将使用辅助方法来注册侦听器。然后使用活动或片段注册,您希望在您的回调发生任何变化时调用该活动或片段 共享引用。 .

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

    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 我们的实践 OnSharedPreferenceChangeListener() 每次 language 值是 set