【发布时间】:2021-05-25 20:27:07
【问题描述】:
我试图在从活动中按下时刷新片段,我尝试使用 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
}
【问题讨论】:
-
请提供错误日志,没有它我们只能猜测您的错误可能是什么
-
不要在 onResume 中分离和附加,而是尝试在那里仅调用 createRecentlyViewedButton(recentlyViewed) 方法。您可以从 onCreateView() 中删除该调用。以你正在做的方式“刷新”片段不是一个好习惯。
-
@TiagoOrnelas 我替换了 onResume() 的分离和附加,并将其更改为调用该函数,它起作用了,谢谢
标签: android kotlin android-fragments