Android onBackPressed()回到之前的Fragment / Activity

时间:2016-04-03 09:35:11

标签: android android-activity fragment onbackpressed

我在我的项目中使用导航抽屉

我的项目包含一些片段文件以及一些活动文件

我只需要文件中的任何内容onBackPressed()它应该回到以前的片段到活动,反之亦然

例如:

开始MainActivity > Fragment > Fragment > Activity

onBackPressed()Activity > Fragment > Fragment > MainActivity ---然后dialogBox退出或不退出

我尝试了其他StackOverflow帖子中的一些方法,但没有一篇文章对我有用

尝试过的例子

@Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }
        else {
            HomeFragment fragment = new HomeFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();

            if (getFragmentManager().getBackStackEntryCount() == 0) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setCancelable(false);
                builder.setMessage("Do you want to Exit?");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //if user pressed "yes", then he is allowed to exit from application
                        finish();
                    }
                });
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //if user select "No", just cancel this dialog and continue with app
                        dialog.cancel();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

添加/替换/提交片段事务时,需要调用addToBackStack。当您单击链接或按钮时,或者您正在进行导航时,此时您需要启动片段事务,用新片段替换现有片段。重要的是,在提交事务之前需要addToBackStack

这样做是将当前片段添加到backstack中,因此当用户按下新片段中的后退按钮时,会将其恢复到上一个​​片段

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

fragmentTransaction.replace(R.id.fragment_container, new_fragment_class).addToBackStack(null).commit();

您不会像现在这样在onBackPressed方法中执行此操作,但是当用户点击导航抽屉中的某些内容时。因此,您需要一种方法来捕获用户对导航菜单项的点击。例如:

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    switch (id) {
        case R.id.nav_new:
            //do your add/replace fragment transaction here
            break;
    }    
}

一旦你有了实际的backstack(上面的代码),看起来你的if (getFragmentManager().getBackStackEntryCount() == 0...代码应该可行。这只会检查当前的Backstack中是否有任何项目,如果没有,则显示一个对话框

编辑:

下面举例说明如何使用导航抽屉处理片段事务:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    NavigationView navigationView = null;
    Toolbar toolbar = null;
    FragmentManager fragmentManager = getSupportFragmentManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //set initial fragment to 'new' instead
        addFragment(new NewFragment(), true);

        //Set the toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Set navigation drawer
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            //put your alert dialog code here
            //if (getFragmentManager().getBackStackEntryCount() == 0) ...
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        // Replace these with your own menu items
        switch (id) {
            case R.id.nav_start:
                addFragment(new StartFragment(), true);
                break;
            case R.id.nav_save:
                addFragment(new SaveFragment(), true);
                break;
            case R.id.nav_raw:
                addFragment(new RawFragment(), true);
                break;
            case R.id.nav_gyroscope:
                addFragment(new GyroscopeFragment(), true);
                break;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void addFragment(Fragment fragment, Boolean addToBackStack) {
        if (fragment != null) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
                        .addToBackStack(null)
                        .commit();
        }
    }
}