简体   繁体   中英

How do I switch which is already in a fragment to move from one fragment to another (Java) in Android?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM