1

I have two fragments as SignInFragment and SignUpFragment. First MainActivity calls SignInFragment with this code.

//MainActivity
if (savedInstanceState == null) {
    signInFragment = new SignInFragment();
    signUpFragment = new SignUpFragment();

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.frame_holder,signInFragment);
    fragmentTransaction.commit();
}

How can I call SignUpFragment after clicking a sign-up button in SignInFragment. I have got a reference to the button:

//SignInFragment    
Button buttonSignUp = view.findViewById(R.id.button_sign_up);
Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
Cafer Mert Ceyhan
  • 1,640
  • 1
  • 13
  • 17
  • I suggest you become very familiar with [the Official Android documentation](https://d.android.com). You should start by checking out the docs about [Fragments](https://developer.android.com/guide/components/fragments#Transactions). A google search will also turn up lots of information for you. – Code-Apprentice Jul 31 '18 at 00:42

2 Answers2

4

You need to override the onClick for the signup button first.

and place this code inside

      FragmentTransaction fragmentTransaction = 
              getSupportFragmentManager().beginTransaction();
              fragmentTransaction.replace(R.id.frame_holder, signInFragment);
              fragmentTransaction.commit();

and as sudhanshu-vohra said you must replace it not add it to the frame_holder.

Ali Habbash
  • 777
  • 2
  • 6
  • 29
0

Override their respective onClick() methods to respond to click events on the Buttons and write the code to replace the fragments in the following manner:

public void onClick(View v) {
    switch(v.getId()){
     case R.id.button_sign_up:
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame_holder, signInFragment);
            fragmentTransaction.commit();
    }
}

Note: You need to replace the fragment and not add the fragment when adding any fragment second time(or any consecutive time) because add will simply overlay the other fragment on the first fragment. For more information, refer this answer.

Sudhanshu Vohra
  • 1,345
  • 2
  • 14
  • 21