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
Button ok= view.findViewById(R.id.btSettingOK);
Fragment me=this;
ok.setOnClickListener( new View.OnClickListener(){
public void onClick(View v){
getActivity().getFragmentManager().beginTransaction().remove(me).commit();
}
});
getActivity().onBackPressed
does the all you need. It automatically calls the onBackPressed method in parent activity.
Try this one
getActivity().finish();
If you need to handle the action more specifically with the back button you can use the following method:
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK )
{
onCloseFragment();
return true;
} else {
return false;
}
}
});
Try this:
ft.addToBackStack(null); // ft is FragmentTransaction
So, when you press back-key, the current activity (which holds multiple fragments) will load previous fragment rather than finishing itself.
Try this:
public void removeFragment(Fragment fragment){
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
}