I have try to close the current fragment by using Imagebutton.
I am in Fragment-A and it will turn to the Fragment-B when I click the button.
And when I clic
From Fragment A, to go to B, replace A with B and use addToBackstack()
before commit()
.
Now From Fragment B, to go to C, first use popBackStackImmediate()
, this will bring back A. Now replace A with C, just like the first transaction.
if you need in 2020
Objects.requireNonNull(getActivity()).onBackPressed();
I change the code from getActivity().getFragmentManager().beginTransaction().remove(this).commit();
to
getActivity().getFragmentManager().popBackStack();
And it can close the fragment.
For those who need to figure out simple way
Try getActivity().onBackPressed();
In your Fragments onCreateView(...)
you can remove a view by calling container.removeView(view);
.
So if you want to remove the fragment, then view
should be the return value of onCreateView
,
for example
public View onCreateView(...){
final View view = inflater.inflate(R.layout.your_fragments_layout,container,false);
//Do something
finishButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
container.removeView(view);
}
});
return view;
}
This is a Kotlin way of doing this, I have created button in fragment layout and then set onClickListner in onViewCreated.
according to @Viswanath-Lekshmanan comment
override fun onViewCreated(view: View?, savedInstanceState: Bundle?)
{
super.onViewCreated(view, savedInstanceState)
btn_FragSP_back.setOnClickListener {
activity?.onBackPressed()
}
}