Reputation: 2252
When i try to remove the fragment, the if check is not working correctly My code is
public void onClick(View v) {
switch (v.getId()) {
case R.id.vehicle_button:
if(getSupportFragmentManager().findFragmentById(R.id.relative_tread_fragment).isVisible()){
getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.relative_tread_fragment)).commit();
}
flag = true;
break;
case R.id.trailer_button:
flag = false;
break;
case R.id.button_search:
if (VRN.contains(actv.getText().toString()) && flag == true) {
getSupportFragmentManager().beginTransaction().replace(R.id.relative_tread_fragment, fragment1).commit();
}
else if (VRN.contains(actv.getText().toString()) && flag == false)
{
getSupportFragmentManager().beginTransaction().replace(R.id.relative_tread_fragment, fragment2).commit();
}
else {
flag = true;
Custom_Dialog(v);
}
i am trying to remove if any fragment is already present, but if there is no fragment, then that if block which checks if any fragment is there doesn't work and the app tries to remove the fragment which is not there and the app crashes
any suggestions how i should chk if there is a fragment or not ?
Upvotes: 0
Views: 92
Reputation: 527
Try this;
Upvotes: 0
Reputation: 1710
You can use this to check whether a certain fragment is inside a certain holder layout:
Fragment yourFrag = getSupportFragmentManager().findFragmentById(R.id.yourFragmentHolderView);
return yourFrag != null && yourFrag instanceof whateverFragment;
You can then use methods like isVisible() etc on that fragment and remove it if you want to!.
So for example, I have an Activity which contains an inbox OR outbox fragment. If I want to know which one is active I use one of the following methods:
public boolean checkIsInbox() {
Fragment inboxFrag = getSupportFragmentManager().findFragmentById(LIST_FRAG_HOLDER_ID);
return inboxFrag != null && inboxFrag instanceof InboxListFragment;
}
public boolean checkIsOutbox() {
Fragment outboxFrag = getSupportFragmentManager().findFragmentById(LIST_FRAG_HOLDER_ID);
return outboxFrag != null && outboxFrag instanceof OutboxListFragment;
}
Upvotes: 1
Reputation: 1763
if you can you should use replace instead of remove. If you want to remove all fragments then just empty the back stack like:
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
Upvotes: 0