FernandoPaiva
FernandoPaiva

Reputation: 4460

Finish a fragment with onBackPressed true?

I have a Fragment(TimerToAnswer) that I implemented onBackPressed() of a ActionBarActivity. Does Fragment can't return when isVisible true because there is a timer to answer a question. After the question is answer in Fragment(TimerToAnswer) I make redirect to other Fragment(ChooseQuestion) to choose other question to answer. In this stage when I pressed button back of device its return to Fragment(TimerToAnswer) again and I don't wanna that. For this problem, I'm trying finish() the Fragment(TimerToAnswer) but I can't do it.

I tried getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); or getActivity().getSupportFragmentManager().popBackStack();

Here how I'm trying

ActionBarActivity

public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{


@Override
    public void onBackPressed() {   
        TimerToAnswer tt = (TimerToAnswer)getSupportFragmentManager().findFragmentByTag("TimerToAnswer");

        if(tt != null && tt.isVisible()){
            return;
        }else{
            super.onBackPressed();
        }
    }
    }

Fragment TimerToAnswer

public class TimerToAnswer extends Fragment implements AdapterView.OnItemClickListener {

   if(answer){
      FragmentTransaction ft;
                    Fragment frag;

                        frag = new ChooseQuestion();
                        Bundle params = new Bundle();
                        ft = getFragmentManager().beginTransaction();
                        ft.replace(R.id.fl, frag);                      
                        ft.addToBackStack("back");
                        ft.commit();

                        removeFrag();       
   }

   private void removeFrag(){
            //getActivity().getSupportFragmentManager().popBackStack();
            getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
        }

}

Upvotes: 0

Views: 245

Answers (1)

Adam S
Adam S

Reputation: 16394

The reason it's returning to your TimerToAnswer fragment when the user presses back from ChooseQuestion is because of this line:

ft.addToBackStack("back");

What that does, as per the documentation:

Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.

To fix this, just remove that line.

Upvotes: 1

Related Questions