Cafer Mert Ceyhan
Cafer Mert Ceyhan

Reputation: 1756

Which best way for using multiple Fragment?

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);

Upvotes: 1

Views: 86

Answers (2)

Ali Habbash
Ali Habbash

Reputation: 797

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.

Upvotes: 4

Sudhanshu Vohra
Sudhanshu Vohra

Reputation: 1395

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.

Upvotes: 0

Related Questions