gpt4 book ai didi

android - Kotlin Android - 当主 Activity 添加项目时从 fragment 刷新 ListView

转载 作者:行者123 更新时间:2023-11-29 00:53:23 26 4
gpt4 key购买 nike

我有一个带有 2 个子菜单的 BottomNavigationView,Home 和 Email,以及一个可以将项目添加到 Email 的 fab。

我正在使用 fragment EmailFragment 来处理子菜单点击。现在,在 EmailFragment 中我有一个 ListView。 BottomNavigationMenu 中的 fab 能够从 MainActivity 添加项目到 EmailFragment ListView 并且工作正常。问题是,只有当我重新打开 EmailFragment 及其布局时,我才会看到新的 ListView 项目。

我希望当我向此 ListView 添加项目时无需重新打开 fragment 。

这是我在 MainActivity 中添加项目的方式:

 positiveButton.setOnClickListener{

if(dialogView.email_textInput.text!!.isEmpty() || dialogView.email_password_textInput.text!!.isEmpty()) {
Toast.makeText(this, resources.getString(R.string.empty_fields), Toast.LENGTH_LONG).show()
}

else{

emailAddresses.add(dialogView.email_textInput.text!!.toString())


adapter.notifyDataSetChanged()

saveData()

}
}

这是我从 MainActivity 保存数据的方式:

private fun saveData() {
val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
val editor = sharedPreferences.edit()
val gson = Gson()
val json = gson.toJson(emailAddresses) //convert ArrayList to JSON (shared preferences can't handle ArrayList)
editor.putString("emailAddresses", json) //save the new JSON with values
editor.apply() //apply new changes
}

这是我从 EmailFragment 获取数据的方式:

private fun loadData() {
val sharedPreferences = this.activity!!.getSharedPreferences("shared preferences", MODE_PRIVATE)
val gson = Gson()
val json = sharedPreferences.getString("emailAddresses", null)
val type = object : TypeToken<ArrayList<String>>() {
}.type

when (json) {
null -> emailAddresses = ArrayList() //if json is null, so empty, values is just an empty ArrayList
else -> emailAddresses = gson.fromJson(json, type) //got JSON values and convert them back to ArrayList

}
}

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?

): View? {

loadData()

val adapter = ArrayAdapter(this.activity!!.applicationContext, R.layout.listview_text, emailAddresses)
adapter.notifyDataSetChanged()

val mainView = inflater.inflate(R.layout.fragment_email, container, false)

mainView.email_listView.adapter = adapter

return mainView
}

最佳答案

使用LiveData,LiveData会观察变化并自动刷新adapter

关于android - Kotlin Android - 当主 Activity 添加项目时从 fragment 刷新 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57374439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com