Friday, 11 January 2019

Close Fragment on back press or any button press.

This solution is for when You have one activity and inside that activity you have a fragment .After launching the fragment if you want close only fragment on back press or any close button click than following code will work:-
1. Fist of all we have override the onBackPressed() in the Activity where u will launch the fragment and than You just right following code:-
mFrameLayout is FrameLayout which I took inside Activity xml layout.

@Override    public void onBackPressed() {
        Log.d("supriya", "onBackPressed");
        super.onBackPressed();
mFrameLayout.setVisibility(View.GONE);
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragmentList =  fragmentManager.getFragments();
for (Fragment fragment : fragmentList)
{
    if(fragment instanceof VIdeoListFragment ){
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().remove(fragment);
        fragmentTransaction.commitNow();
    }
}
}

2. On any close button click inside fragment  following line we have to call:-

closeButton.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        if(getActivity() != null)
        getActivity().onBackPressed();
    }
});

No comments:

Post a Comment