Mariano Pelizzari Mariano Pelizzari - 3 months ago 12
Android Question

remove fragment on a button touch

I just need to remove a fragment when a button in it is tapped

public static class EditNameDialog extends DialogFragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_find_in_page, container);
...
Button cancelButton = (Button) view.findViewById(R.id.cancel_button);
cancelButton.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View arg0, MotionEvent arg1) {
//remove the fragment here
return false;
}
});
return view;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
}
}


I just need to remove the fragment when the button is tapped

Answer

You can remove the fragment with use below code:

 //remove the fragment from transaction manager
    FragmentManager frgManager = getSupportFragmentManager();
    Fragment fragment = frgManager.findFragmentByTag(tagName);
    if (fragment != null) {
        FragmentTransaction ft = frgManager.beginTransaction();
        ft.remove(fragment).commit();
    }
Comments