在RecyclerView中按sharedpreference显示Kotlin商店列表



我正在尝试存储列表,我从RecyclerView共享首选项的模态类存储中获得旋转器,但我只获得最后一项选择,而不是从旋转器中进行多次选择

spinner.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener{
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
val data_  = ArrayList<Model>()
data_.add(Model(department[p2]))
val gson: Gson =Gson()
val json:String = gson.toJson(data_)
val editor:SharedPreferences.Editor = sharedPreferences.edit()
editor.putString("list",json)
editor.apply()
}

填补适配器

val gson: Gson =Gson()
val json: String? = sharedPreferences.getString("list",null)
val type= object :TypeToken<ArrayList<Model>>(){
}.type
data_ = gson.fromJson(json,type)
if (data_ == null){
Toast.makeText(this,"null",Toast.LENGTH_SHORT).show()
}
else{
val rec = binding.recyclerView
rec.layoutManager = LinearLayoutManager(this)
val adapter = AddEditTextAdapter(data_)
rec.adapter = adapter
}

问题是每次您总是在onItemSelectedListener函数中重新初始化data_数组。
您可以声明单独的函数来检索和设置您的SharedPreference:

fun getData(): ArrayList<Model>? {
val json = sharedPreferences.getString("list", "")
if (json == "") return null
val type = object : TypeToken<ArrayList<Model>>(){ }.type
return Gson().fromJson(json, type)
}
fun setData(data: ArrayList<Model>) {
val json = Gson().toJson(data)
sharedPreferences.edit()
.putString("list", json)
.apply()
}

并在代码中使用这些函数:

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
val data_ = getData() ?: arrayListOf<Model>()
// Add data to existing values
data_.add(Model(department[p2]))
// Update prefs
setData(data_)
}
}

新适配器的代码:

val data_ = getData()
if (data_ == null){
Toast.makeText(this,"null",Toast.LENGTH_SHORT).show()
}
else {
val rec = binding.recyclerView
rec.layoutManager = LinearLayoutManager(this)
val adapter = AddEditTextAdapter(data_)
rec.adapter = adapter
}

相关内容

  • 没有找到相关文章