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.
CodePudding user response:
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.
CodePudding user response:
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