0

I am actually working on fragments instead of activities .So on navigation drawer item click different fragments appear on the screen.Based on my code, if i am moving from Activity A to fragment b,then fragment c,again to b,then if i will click back button,then it will navigate me to the MainActivity A.But here is the problem.when i want to add confirm on exit dialog box on the MainActivity onBackPress(),it appears every time i click the back button regardless of which page is open,But i want it to appear only when there is no fragments left in the back stack.I need some help on that issue.

    Here is my MainActivity code:--

    package archerpenny.impdrawerfragment;


import android.content.DialogInterface;
import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;

import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

import android.view.MenuItem;

import android.view.View;


public class MainActivity extends AppCompatActivity  {
    ActionBarDrawerToggle mDrawerToggle;
    RecyclerView.Adapter mAdapter;
    RecyclerView recyclerView;
    DrawerLayout mDrawerLayout;
    FragmentManager fragmentManager;
    Fragment blankFragment=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAdapter = new NavigationDrawerAdapter(this);
        mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        NavigationDrawerAdapter adapter;

        recyclerView = (RecyclerView)findViewById(R.id.DrawerList);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(llm);
        recyclerView.setAdapter(mAdapter);

        getSupportActionBar().setDisplayShowTitleEnabled(false);

        mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.open,R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        // do whatever

                        if(position==0)
                        {
                            blankFragment=new BlankFragment();

                        }
                        if (position==1)
                        {
                            blankFragment=new BlankFragment2();
                        }
                        if (position==2)
                        {
                            blankFragment=new BlankFragment3();
                        }
                        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                        getSupportFragmentManager().popBackStack();
                        fragmentManager.beginTransaction()
                                .add(R.id.container_body, blankFragment).addToBackStack("fragBack").commit();
                        mDrawerLayout.closeDrawers();
                    }
                })
        );
    }
    @Override
    public void onBackPressed() {
        if(getSupportFragmentManager().findFragmentByTag("fragBack") != null)
        {
            getSupportFragmentManager().popBackStack();
            getSupportFragmentManager().beginTransaction().add(R.id.container_body, blankFragment).addToBackStack("fragBack").commit();
        }
        else {
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Closing Activity")
                    .setMessage("Are you sure you want to close this activity?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }

                    })
                    .setNegativeButton("No", null)
                    .show();



        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
4

2 回答 2

2

I'm not sure why you are relying on reusing that "fragBack" tag? The backstack provides everything you need. Try something like the following:

public void onBackPressed() {
    FragmentManager fragMgr = getSupportFragmentManager();
    if (fragMgr.getBackStackEntryCount() > 0) {
        fragMgr.popBackStackImmediate(); //or whatever
    } else {
        //show the dialog 
    }
}
于 2015-08-04T14:05:35.183 回答
0

Inside your activity which handles all the fragments , use

@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {   

super.onBackPressed();      

//you can add your alertdialog code here and after pressing positive button of alertdialog you can call super.onBackPressed()      
}
else {            
      getSupportFragmentManager().popBackStack();            
   }
}

When the fragment backstack entry count is 0 , it means all the fragments are popped out of the backstack. So you just execute the super.onBackPressed() then. However when the stack is not empty , when you press back button you need to pop the top most fragment from the backstack so that proper back navigation happens.

Hope this helps you. However if you are not sure if you are adding/replacing your fragments correctly or not , please refer my answer in this post.

于 2015-08-04T17:59:27.097 回答