简体   繁体   English

强制 android 在选项卡更改时销毁片段? (viewpager的生命周期)

[英]force android to destroy fragment on tab change? (lifeCycle of viewpager)

I have two tabs in my app with two RecyclerView that when I click on one item in the first tab it adds one item to the second tab (download link to download manager) but the user can't see the change until the fragment onDestroy and again onCreate (rotate, exit, going to the third tab) I think it happens because of the lifeCycle of fragment in viewPager that keeps the previous tab.我的应用程序中有两个带有两个RecyclerView的选项卡,当我单击第一个选项卡中的一个项目时,它会将一个项目添加到第二个选项卡(下载链接到下载管理器),但用户无法看到更改,直到片段onDestroy和再次onCreate (旋转,退出,转到第三个选项卡)我认为这是因为lifeCycle中片段的viewPager保留了前一个选项卡。

How can I force android to destroy fragment on tab change?如何强制 android 在选项卡更改时销毁片段? I even tried setOnPageChangeListener with interface but it did not work for me, maybe because getItem only runs on fragment creation?我什至尝试过带有接口的setOnPageChangeListener但它对我不起作用,可能是因为getItem仅在片段创建时运行?

Instead of populating your list in onCreate(), you should do it in onResume(). 与其在onCreate()中填充列表,不如在onResume()中进行填充。 Following the Android Activity lifecycle, as soon as your activity/fragment is inactive, onPause() is called - and as soon as you go back to it, onResume() is called. 在Android Activity生命周期之后,一旦您的活动/片段处于非活动状态,就会调用onPause(),一旦回到活动/片段,就会调用onResume()。 So if you are in another tab and switch to your second tab, onResume() will be called and you can create the list from there - no need to destroy the vieiw. 因此,如果您在另一个选项卡中并切换到第二个选项卡,则将调用onResume(),您可以从此处创建列表-无需销毁vieiw。

You can read more on the activity lifecycle here: https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle 您可以在此处了解有关活动生命周期的更多信息: https : //developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

override fun onPause() {覆盖乐趣 onPause() {

    list.clear()
    super.onPause()
}

add this code in your each fragment在您的每个片段中添加此代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM