android - 从活动返回或按下返回时刷新片段
问题描述
我试图在从活动中按下时刷新片段,我尝试使用 onResume() 和 onStop() 并且它有效但是......另一个问题来了。在片段中使用 onResume() 和 onStop() 会使片段刷新太多次,导致应用程序崩溃,我真的不知道我做错了什么,如果你能帮我解决这个问题
我的 onResume() 函数
override fun onResume() {
super.onResume()
//shoudRefreshOnResume is a global var
if (shouldRefreshOnResume) {
val ft: FragmentTransaction = parentFragmentManager.beginTransaction()
ft.detach(this).attach(this).commit()
}
}
我的 onStop() 函数
override fun onStop() {
super.onStop()
shouldRefreshOnResume = true
}
我的 onCreateView() 函数
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_home, container, false)
val foodButton = root.findViewById<Button>(R.id.mainFoodButton)
val recentlyViewed = root.findViewById<LinearLayout>(R.id.recently_viewedView)
foodButton.setOnClickListener {
val intent = Intent(activity, CategoriesActivity::class.java)
startActivity(intent)
}
//createRecentlyViewedButton() is a function
createRecentlyViewedButton(recentlyViewed)
return root
}
解决方案
我通过将 onStop() 函数替换为 onPause() 解决了这个问题,因为活动没有被破坏并且它不再循环 createRecentlyViewedButton() 函数希望这对某人有所帮助
这是我所做的更改
override fun onPause() {
super.onPause()
shouldRefreshOnResume = true
}
和
override fun onResume() {
super.onResume()
//shoudRefreshOnResume is a global var
if (shouldRefreshOnResume) {
val recentlyViewed = activity?.findViewById<LinearLayout>(R.id.recently_viewedView)
createRecentlyViewedButton(recentlyViewed!!)
}
}
推荐阅读
- vue.js - Vuetify 基于断点的响应式网格列
- flutter - 在 Dart 中引用内部类
- flutter - 如何消除此错误:不正确使用 ParentDataWidget
- php - 如何在 Laravel 中将连接结果作为对象数组获取?
- android - 为什么通过 Chrome 自定义标签退出 Android 会丢失 cookie
- sandbox - 用于 arm64 的 Google Sandbox2
- cuda - 如何确定对等访问的状态而不在 cuda-memcheck 中产生警告
- python - AttributeError:“列表”对象没有属性“项目” - Python
- apache-spark - 在写入雪花之前保存 Spark 数据框
- mysql - MySql json反向搜索