回去时片段重叠另一个

时间:2016-07-27 13:04:35

标签: android android-studio android-fragments

我有两个片段的菜单。当我选择第二个片段时,我可以用按钮移动到第三个片段。

MainActivity

    drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
    mDrawerLayout.setDrawerListener(drawerToggle);
    drawerToggle.syncState();

    getSupportActionBar().setTitle("demo");

    mSelectedId = savedInstanceState == null ? R.id.aboutConference : savedInstanceState.getInt("SELECTED_ID");
    itemSelection(mSelectedId);

}

private void setToolbar() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
    }
}

private void initView() {
    mDrawer = (NavigationView) findViewById(R.id.main_drawer);
    mDrawer.setNavigationItemSelectedListener(this);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
}

private void itemSelection(int mSelectedId) {


    switch (mSelectedId) {

        case R.id.aboutConference:
            mDrawerLayout.closeDrawer(GravityCompat.START);
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.main_container, new FirstFragment());
            fragmentTransaction.commit();

            break;


        case R.id.aboutDeveloper:
            mDrawerLayout.closeDrawer(GravityCompat.START);
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.main_container, new SecondFragment());
            fragmentTransaction.commit();
            break;

    }

}

第二个片段

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =
                inflater.inflate(R.layout.second_fragment, container, false);

        Button button = (Button)view.findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.main_container, new ThirdFragment());
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });
        return view;
    }

当我按下后退按钮时,它正常工作。

second fragment

但是如果我移动到第三个片段,选择菜单中的第一个片段并按回按钮,第三个片段重叠第一个片段

problem

我如何解决这个问题?

更新:当我按下按钮时,我不希望我可以从第一个片段返回到第三个片段。

1 个答案:

答案 0 :(得分:0)

由于Shaishavvishal告诉您需要将color放入片段的父视图中。

你需要Override onBackButton按下的方法,并确保从堆栈中删除上一项。

要检查堆栈中是否有项目,请尝试以下代码

fragmentManager1.getBackStackEntryCount()