用另一个片段替换选项卡式滑动视图中的片段视图

时间:2017-05-17 03:15:17

标签: android android-fragments android-tabbed-activity

我正在尝试将我的选项卡式滑动视图中的片段视图替换为另一个片段,但它不会替换或添加片段,而只是在所有选项卡式活动中添加片段的菜单。

我希望在我的swipeview中的特定标签活动中,我可以用另一个片段(FragmentBoy)替换内容(fragmentA),该片段可以覆盖该特定选项卡式活动的特定菜单。当用另一个片段(FragmentGirl)替换内容(fragmentB)时也可以工作。

请我坚持,我需要帮助 -

public class Main2Activity extends AppCompatActivity {
private ViewPager mViewPager;
private int[] tabIcons = {
        R.drawable.ic_grand,
        R.drawable.ic_event,     
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    setupTabIcons();
}
private void setupTabIcons() {
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
}
private void setupViewPager(ViewPager mViewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new FragmentA(), "ONE");
    adapter.addFrag(new FragmentB(), "TWO");    
    mViewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }
    @Override
    public int getCount() {
        return mFragmentList.size();
    }
    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
    @Override
    public CharSequence getPageTitle(int position) {
        return null;
    }
}
public static class FragmentA extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.grand,container,false);
        Button tb=(Button)view.findViewById(R.id.btn_c);
        tb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction().add(R.id.swapfrag, new BOYFragment());
                transaction.commit();
            }
        });
        return view;
    }
}

0 个答案:

没有答案