本文介绍了如何在Kotlin活动中获取ListPreference值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I get ListPreference value of selected option in my activity?

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()
            }
        }
    }

推荐答案

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代替上一个:

Use this PrefManager instead of previous one:

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.发生任何更改时在其中调用回调.

You need to set up a correct listener for your SharedPref. so we'll use a helper method to register the listener. and then register using the activity or fragment where you want your callback to be called at any change to your SharedPref..

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

Setting up correct listener: (you may use anonymous listener also..)

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)

    }

}

现在在需要值的地方注册您的活动:

Now register your activity where value is needed:

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值为set

Now as we pass this as the listener and implement OnSharedPreferenceChangeListener our acticvity's OnSharedPreferenceChangeListener() method will be called each time the language value is set

这篇关于如何在Kotlin活动中获取ListPreference值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 08:03