I have a fragment with two buttons - confirm and cancel. One button, the confirm button, takes the user input from an EditText and convert it to an USSD request. Now I'd like to have the cancel button close that fragment like the negative button on an alertDialog.
I've read many questions a bit similar to this but none of them seems to fullfil my need.
public void onClick(View v) {
switch (v.getId()) {
case R.id.confirmButton:
if (inputField.getText().toString().trim().length() == 16) {
load();
inputField.requestFocus();
} else if (inputField.getText().toString().trim().length() < 16) {
Toast.makeText(getActivity(), R.string.toast_number_not_valid, Toast.LENGTH_SHORT).show();
}
break;
case R.id.cancelButton:
dismiss();
break;
}
}
private void load() {
// bla - bla - bla
}
public void dismiss(){
//dear fragment, I don't need you right now, just dismiss
}
Here I need the dismiss() method.
Any help will be appreciated.
Just call:
getActivity().onBackPressed();
The solution from oskarko work but it brings you back to the main Activity.
If you want your fragment to close from inside your Fragment and you don't want to leave the current Activity, try this approach:
getFragmentManager().beginTransaction().remove(ActivityFragment.this).commit();
Where "ActivityFragment" is the name of your Fragment.
Consider this:
If you add your FragmentManager adds the Fragment to the backStack (fragmentTransaction.addToBackStack(null);
), you should not use this approach, instead use:
getFragmentManager().popBackStack();
The Reason for this is if you close it with the first method, your Fragment is still in the backStack and you have to click the Previous Button twice to get to the previous Activity.
Kotlin:
In Activity:
val fragment = SettingFragment.newInstance()
// always create a new transaction to avoid crash
val mTransaction = fragmentManager.beginTransaction()
mTransaction.add(R.id.settingDrawer, fragment)
mTransaction.commit()
In fragment:
val manager = requireActivity().supportFragmentManager
manager.beginTransaction().remove(this).commit()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With