简体   繁体   English

如何同时重新加载所有片段

[英]How to reload all the fragments at the same time

I have an activity with 2 fragments. 我有一个带有2个片段的活动。 Let's call the activity "MainActivity", the first fragment "FragmentA" and the second fragment "FragmentB". 我们将活动称为“ MainActivity”,将第一个片段称为“ FragmentA”,将第二个片段称为“ FragmentB”。 When I delete an element in FragmentA, I use this method inside the FragmentA to realod it: 当我删除FragmentA中的元素时,我在FragmentA中使用此方法来实现它:

public void reload_fragment() {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.detach(this).attach(this).commit();
}

But I also need to reload the FragmentB at the same time. 但是我还需要同时重新加载FragmentB。 I try to add in the above method that: 我尝试在上述方法中添加:

public void reload_fragment() {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.detach(this).attach(this).commit();
    MainActivity mainActivity = new MainActivity();
    mainActivity.reload_fragments();

And then, in my mainActivity, i have this method: 然后,在我的mainActivity中,我有以下方法:

  public void reload_fragments(){
    viewPager = findViewById(R.id.Viewpager_ID);

    adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(adapter);
    TabLayout tabLayout = findViewById(R.id.tablayout);
    tabLayout.setupWithViewPager(viewPager);
}

But it doesn't work. 但这是行不通的。 I tried to add the same method which is inside the FragmentA into the FragmentB, and then call it by the FragmentA, but again, it says "virtual method on NullObjectReference". 我试图将FragmentA内的相同方法添加到FragmentB中,然后由FragmentA调用它,但是同样,它说“ NullObjectReference上的虚拟方法”。 How can I refresh all the fragments at the same time? 如何同时刷新所有片段?

Form a ViewModel with a MutableLiveData boolean field called say "refresh". 用一个名为“ refresh”的MutableLiveData布尔字段构成一个ViewModel。 Add a method to the ViewModel called "toggleRefresh()" which flips the state of refresh. 在ViewModel中添加一个名为“ toggleRefresh()”的方法,该方法可以翻转刷新状态。 In each fragment, in the onAttatch, observe the refresh field and do the "reload there"? 在每个片段的onAttatch中,观察刷新字段并“重新加载”吗?

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

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