This line of code is misplaced:
Fragment fragment = fm.findFragmentByTag(MAIN);
You have it outside of the onClick()
method, which means that the value of fragment
is determined once (when you create/assign the OnClickListener
) and then reused every time the button is clicked.
Just move that line inside the onClick()
method:
@Override
public void onClick(View view) {
Fragment fragment = fm.findFragmentByTag(MAIN);
if(fragment == null) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content, new MainFragment(), MAIN).addToBackStack(null).commit();
}else{
Toast.makeText(getApplicationContext(), "Fragment already created", Toast.LENGTH_SHORT).show();
Log.i("onCreate():","Fragment Already created");
}
}
solved OnClick button replacing fragment many times with FragmentTransaction, ignoring Tag