简体   繁体   English

如何在 TabsLayout 中将一个片段的内容替换为另一个片段的内容?

[英]How to replace the content of one fragment with another in TabsLayout?

I use a tablayout with two tabs.我使用带有两个选项卡的 tablayout。 Each tab has a viewpager fragment.每个选项卡都有一个 viewpager 片段。 The code:代码:

ALoginFragment AFragment = new ALoginFragment();
BLoginFragment BFragment = new BLoginFragment();
SectionsPageAdapter sectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
sectionsPageAdapter.addFragment(AFragment, "A");
sectionsPageAdapter.addFragment(BFragment, "B");
viewPager.setAdapter(sectionsPageAdapter);
tabLayout.setupWithViewPager(viewPager);

The SectionsPageAdapter is my custom sections page adapter. SectionsPageAdapter是我的自定义部分页面适配器。 The code:代码:

public class SectionsPageAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public SectionsPageAdapter(FragmentManager fragmentManager) {
        super(fragmentManager,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }
}

When I click some button in fragment A I want to replace the content of tab A with tab C .当我单击片段A中的某个按钮时,我想用选项卡C替换选项卡A的内容。 I tried;我试过;

getChildFragmentManager().beginTransaction().replace(fragmentView.getId(), new CLoginFragment())
                .addToBackStack(null).commit();

Where save fragmentView in the A 's onCreateView method.AonCreateView方法中保存fragmentView的位置。 But fragmentView.getId() is -1 for some reason.但出于某种原因, fragmentView.getId()-1 How can I replace the content of A with C ?如何用C替换A的内容?

to replace fragment which are inside viewpager put this function in SectionsPageAdapter要替换 viewpager 中的片段,请将此 function 放入SectionsPageAdapter

public void replaceFragment(int position,Fragment newFragment ){
    mFragmentList.set(position, newFragment);
    notifyDataSetChanged();
}

then call it with the position of fragment that need to be changed and the newFragment然后用需要更改的片段的 position 和 newFragment 调用它

sectionsPageAdapter.replaceFragment(0,new CFragment());// replace ALoginFragment which is at zero index with CFragment

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

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