首页 > 解决方案 > 从活动返回或按下返回时刷新片段

问题描述

我试图在从活动中按下时刷新片段,我尝试使用 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
}

标签: androidkotlinandroid-fragments

解决方案


我通过将 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!!)
        }
    }

推荐阅读