Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a fragment on button click which is inside that fragment

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.

like image 793
esQmo_ Avatar asked Mar 27 '17 10:03

esQmo_


3 Answers

Just call:

getActivity().onBackPressed();
like image 130
oskarko Avatar answered Nov 04 '22 01:11

oskarko


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.

like image 20
DrGregoryHouse Avatar answered Nov 04 '22 02:11

DrGregoryHouse


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()
like image 37
Homan Huang Avatar answered Nov 04 '22 01:11

Homan Huang