I am looking for a way to have an "Are you sure you have finished?" alert box to come up when the user presses the back navigation button whilst on the edit note and add note fragment but not whilst they're on the view note fragment. Below I have attached code from the activity which each fragment is linked to. If you need more of my code from different areas, please let me know.
public class NoteDetailActivity extends AppCompatActivity {
public static final String NEW_NOTE_EXTRA = "New Note";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_detail);
createAndFragment();
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}
private void createAndFragment(){
Intent intent = getIntent();
MainActivity.FragmentToLaunch fragmentToLaunch = (MainActivity.FragmentToLaunch) intent.getSerializableExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch(fragmentToLaunch){
case EDIT:
NoteEditFragment noteEditFragment = new NoteEditFragment();
setTitle(R.string.edit_fragment_title);
fragmentTransaction.add(R.id.note_container, noteEditFragment, "NOTE_EDIT_FRAGMENT");
break;
case VIEW:
NoteViewFragment noteViewFragment = new NoteViewFragment();
setTitle(R.string.view_fragment_title);
fragmentTransaction.add(R.id.note_container, noteViewFragment, "NOTE_VIEW_FRAGMENT");
break;
case CREATE:
NoteEditFragment noteCreateFragment = new NoteEditFragment();
setTitle(R.string.create_fragment_title);
Bundle bundle = new Bundle();
bundle.putBoolean(NEW_NOTE_EXTRA, true);
noteCreateFragment.setArguments(bundle);
fragmentTransaction.add(R.id.note_container, noteCreateFragment, "NOTE_CREATE_FRAGMENT");
break;
}
fragmentTransaction.commit();
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
NoteDetailActivity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
Do this by getting the fragment tag
get tag like this
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
String tag = fragment.getTag(); // This will return the tag of fragment
Then use if-else to do the task
if (tag.equalsIgnoreCase("Home")) {
// Open aLERT box
}else if (tag.equalsIgnoreCase("Home2")) {
// Open aLERT box
}else if (tag.equalsIgnoreCase("Home2")) {
// Open aLERT box
}else{
// dO STUFF HERE
}
Don't forget to add the tag of fragment