1

This is my main activity where I am calling my fragments:

public class what extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;


    private ListView mDrawerList;
    private ArrayAdapter<String> mAdapter;
    private FragmentTransaction fragmentTransaction;
    NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_what);


        mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
        mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        fragmentTransaction= getSupportFragmentManager().beginTransaction();


        fragmentTransaction.add(R.id.main_content,new mainfrag());
        fragmentTransaction.commit();

        ActionBar actionBar= getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        navigationView=(NavigationView)findViewById(R.id.nav_view);
        navigationView.getMenu().getItem(1).setChecked(false);
        navigationView.getMenu().getItem(0).setChecked(true);
        navigationView.getMenu().getItem(2).setChecked(false);
        navigationView.getMenu().getItem(3).setChecked(false);


        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_main:
                        navigationView.getMenu().getItem(1).setChecked(false);
                        navigationView.getMenu().getItem(2).setChecked(false);
                        navigationView.getMenu().getItem(3).setChecked(false);
                        navigationView.setCheckedItem(R.id.nav_main);
                        mDrawerLayout.closeDrawers();
                        fragmentTransaction=getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.main_content, new mainfrag());
                        fragmentTransaction.commit();
                        getSupportActionBar().setTitle(("SGPA and CGPA Calculator"));
                        item.setChecked(true);
                        break;
                    case R.id.nav_savedcal:
                        navigationView.getMenu().getItem(0).setChecked(false);
                        navigationView.getMenu().getItem(2).setChecked(false);
                        navigationView.getMenu().getItem(3).setChecked(false);
                        navigationView.setCheckedItem(R.id.nav_savedcal);
                        mDrawerLayout.closeDrawers();
                        fragmentTransaction=getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.main_content, new savedFragment());
                        fragmentTransaction.commit();
                        getSupportActionBar().setTitle(("Saved Calculations"));
                        item.setChecked(true);
                        break;
                    case R.id.nav_upldoc:
                        navigationView.getMenu().getItem(0).setChecked(false);
                        navigationView.getMenu().getItem(1).setChecked(false);
                        navigationView.getMenu().getItem(3).setChecked(false);
                        navigationView.setCheckedItem(R.id.nav_upldoc);
                        mDrawerLayout.closeDrawers();
                        fragmentTransaction=getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.main_content, new uploadedfragment());
                        fragmentTransaction.commit();
                        getSupportActionBar().setTitle(("Uploaded documents"));
                        item.setChecked(true);
                        break;
                    case R.id.nav_site:

                        navigationView.getMenu().getItem(0).setChecked(false);
                        navigationView.getMenu().getItem(1).setChecked(false);
                        navigationView.getMenu().getItem(2).setChecked(false);
                        navigationView.setCheckedItem(R.id.nav_site);
                        mDrawerLayout.closeDrawers();
                        fragmentTransaction=getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.main_content, new resultsite());
                        fragmentTransaction.commit();
                        getSupportActionBar().setTitle(("VTU Results"));
                        item.setChecked(true);
                        break;

                }

                return false;
            }
        });

    }


    public boolean onOptionsItemSelected(MenuItem item ){
        if(mToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override

    public void onBackPressed() {

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case DialogInterface.BUTTON_POSITIVE: {
                            finish();
                        }


                        break;

                        case DialogInterface.BUTTON_NEGATIVE:
                            break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure you want to exit?").setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
    }
}

This is my default fragment :

public class mainfrag extends Fragment {

    private View view;
    private AdView adView;
    private Button button10;
    private Button button11;

    public mainfrag() {
        // Required empty public constructor
    }


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

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        view = inflater.inflate(R.layout.fragment_mainfrag, container, false);

        adView = view.findViewById(R.id.adView);

        button10 = (Button) view.findViewById(R.id.button10);
        button10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openmainactivity();
            }
        });
        button11 = (Button) view.findViewById(R.id.button11);
        button11.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openscheme();
            }
        });
        return view;
    }

    public void openmainactivity() {
        Intent intent = new Intent(getContext(), MainActivity.class);
        startActivity(intent);
    }
    public void openscheme(){
        Intent intent=new Intent(getContext(), scheme.class);
        startActivity(intent);
    }
}

This is one of the other fragments:

public class savedFragment extends Fragment {


    RecyclerView recyclerview;
    adapter_sgpa recyclerAdapter;

    ArrayList<POJO> sgpaArrayList;

    public savedFragment() {
        // Required empty public constructor
    }

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

        FragmentTransaction tx = getChildFragmentManager().beginTransaction();
        tx.replace(R.id.container, new sgpa_frag());
        tx.commit();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int id = item.getItemId();
            Fragment fragment = null;
            switch (id) {
                case R.id.navigation_sgpa:
                    sgpa_frag sf = new sgpa_frag();
                    FragmentManager fragmentManager = getChildFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.container, sf).commit();
                    return true;
                case R.id.navigation_cgpa:
                    cgpa_frag cf = new cgpa_frag();
                    fragmentManager = getChildFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.container, cf).commit();
                    return true;
            }
            return false;
        }
    };

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

        BottomNavigationView nav = (BottomNavigationView) v.findViewById(R.id.bottom_navigation);
        nav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        return v;
    }
}

What changes should I make in this code so that I am able to move back from the other fragments to the main fragment on pressing back button ?

hosseinAmini
  • 2,184
  • 2
  • 20
  • 46
  • Does this answer your question? [get the latest fragment in backstack](https://stackoverflow.com/questions/9702216/get-the-latest-fragment-in-backstack) – hosseinAmini Mar 28 '20 at 06:24
  • Does this answer your question? [Difference between add(), replace(), and addToBackStack()](https://stackoverflow.com/questions/18634207/difference-between-add-replace-and-addtobackstack) – Ryan M Mar 29 '20 at 08:13

2 Answers2

0

Maintain one boolean variable to check current fragment is MainFragment or not.

if its not MainFragment -> replace MainFragment

Else -> super.onBackPressed()

ex:

 private boolean isMainFragment=true; //make it false when move to other fragment


@Override

public void onBackPressed() {
  if(!isMainFragment){
      isMainFragment=true;
     //replace your MainFragment
    }
  else{
   //your logic show dialog or super.onBackPressed()
  }

}
Ranjithkumar
  • 16,071
  • 12
  • 120
  • 159
0

Ithink I know what you need. have a look at the last part of this documentation

"You can add a fragment transaction to the back stack. The back stack keeps track of actions in your app which can be backtracked when the user clicks Android's standard "back" button on the device. If you add a fragment transaction to the back stack then the transaction can be backtracked (reversed) with a click on the back button on the device" quotet from Jenkov

simply do fragmentTransaction.addToBackStack(null) on your main activity before you do the commit this will allow you to travel back using the back button

if you always want to travel back to the main fragment then you want to only add the main fragment to the backstack that way on pressing the back button you will always land there

in this part of your oncreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_what);


    mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
    mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();

    fragmentTransaction= getSupportFragmentManager().beginTransaction();


    fragmentTransaction.add(R.id.main_content,new mainfrag());
    //HERE YOU PUT THE CODE V
    fragmentTransaction.addToBackStack(null);
    //HERE YOU PUT THE CODE ^
    fragmentTransaction.commit();

    ActionBar actionBar= getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    // ALL THE OTHER STUFF COMMING AFTER
quealegriamasalegre
  • 2,887
  • 1
  • 13
  • 35
  • Where should I place this code? MySecondFragment mySecondFragment = new MySecondFragment(); getFragmentManager().beginTransaction() .replace(R.id.fragmentParentViewGroup, mySecondFragment) .addToBackStack(null) .commit(); –  Mar 29 '20 at 09:58
  • in main activity in the top section where you are adding the mainfrag. cause you want that one to be remembered – quealegriamasalegre Mar 29 '20 at 16:46
  • I have already put this - fragmentTransaction.addToBackStack(null). Don't I need to write this code anywhere? - MySecondFragment mySecondFragment = new MySecondFragment(); getFragmentManager().beginTransaction() .replace(R.id.fragmentParentViewGroup, mySecondFragment) .addToBackStack(null) .commit(); I was asking about this. –  Mar 30 '20 at 05:07
  • well it depends on what you want, is there a third fragment that comes after the second one? if you are in the third one and press the back button what do you want to happen, go back to main or to the second? this is a bit hard to explain so i suggest you simply try it out adding addToBackStack(null) to all of them first and then just to the main one and see the differences in behaviour. and then you keep what works for you – quealegriamasalegre Mar 30 '20 at 05:14
  • No. It did not. –  Mar 30 '20 at 05:54
  • I have given the code for the main activity and 2 fragments. I have 4 fragments in the main activity. One of them is the default one, that is the main frag. All of them open using a navigation drawer on the left. I want that whenever back button is pressed in the remaining 3 fragments, they navigate back to the mainfrag. And when the back button is pressed in the main frag it displays a dialog box as given in the mainactivity. –  Mar 30 '20 at 05:58
  • did you try adding them all to backstack – quealegriamasalegre Mar 30 '20 at 06:04
  • I have added them to backstack. But what next? –  Mar 30 '20 at 08:28
  • Each time I am pressing the back button from any fragment I am getting the dialog box prompting whether to exit or not the according to the code that I have written in the onBackPressed method of the main activity, rather it should go back to the main fragment. –  Mar 30 '20 at 08:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210573/discussion-between-sneha-and-quealegriamasalegre). –  Mar 30 '20 at 09:00