skip to Main Content

I have linked a switch to shift from Fragment1 to Fragment2 but I do not know how to return to Fragment1 if the switch is clicked again.

2

Answers


  1. Do not put the switch inside fragment. You should include the switch in parent layout and change the fragment when switch is clicked.

    For eg;

    You include switch in linear layout below that layout you have framelayout in which you are committing the fragments.

    Login or Signup to reply.
  2. A possible solution: use switch.setOnCheckedChangeListener and transaction.replace. For example:

    public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fTrans.add(R.id.your_fragment_container, frag1);
    
        Switch switch = findViewById(R.id.switch);
        if (switch != null) {
            switch.setOnCheckedChangeListener(this);
        }
        frag1 = new Fragment1();
        frag2 = new Fragment2();
    }
    
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            fTrans = getFragmentManager().beginTransaction();
            if(isChecked){
                fTrans.replace(R.id.your_fragment_container, frag2);
            }else{
                fTrans.replace(R.id.your_fragment_container, frag1);
            }
    }
    

    }

    R.id.your_fragment_container is a layout for your two fragments

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search