【问题标题】:refresh the fragment when getting back from an activity or pressing back从活动返回或按下返回时刷新片段
【发布时间】: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


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
相关资源
最近更新 更多