How to Get a Fragment to Remove Itself, I.E. Its Equivalent of Finish()

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?

Step #1: Have Df tell D "yo! we got the OK click!" via calling a method, either on the activity itself, or on an interface instance supplied by the activity.

Step #2: Have D remove the fragments via FragmentManager.

The hosting activity (D) is the one that knows what other fragments are in the activity (vs. being in other activities). Hence, in-fragment events that might affect the fragment mix should be propagated to the activity, which will make the appropriate orchestration moves.

remove the last fragment when leaving activity

This is a little more elegant way of doing it...

I forgot about the onStart()... it is called when the activity is first started. To avoid the fragment being popped upon first opening the application a polymorphic check is applied in the if statement

public class MainActivity extends AppCompatActivity {

private FrameLayout contentFrame;
private FragmentManager fm;
private Button nextButton;

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

contentFrame = (FrameLayout) findViewById(R.id.content_frame);

fm = getSupportFragmentManager();

FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.content_frame, new F1()).commit();

nextButton = (Button) findViewById(R.id.next);

nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(fm.findFragmentById(R.id.content_frame).getClass() == F1.class) {
FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("F2");
ft.add(R.id.content_frame, new F2());
ft.commit();
} else {
startActivity(new Intent(MainActivity.this, ActivityTwo.class));
}
}
});

}

@Override
protected void onStart() {
super.onStart();
if(fm.findFragmentById(R.id.content_frame).getClass() == F2.class) {
fm.popBackStackImmediate("F2", FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
}

Best of luck. Code has been tested as working.

How to open a fragment from another fragment using binding?

Try this code plz:

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.home_layout, new ChatFragment(), "second fragment"); //My second Fragment
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();


Related Topics



Leave a reply



Submit