简体   繁体   English

在 Android 中,如何切换已经在一个片段中的片段以从一个片段移动到另一个片段(Java)?

[英]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.我已经链接了一个从 Fragment1 切换到 Fragment2 的开关,但是如果再次单击该开关,我不知道如何返回到 Fragment1。

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 .一个可能的解决方案:使用switch.setOnCheckedChangeListenertransaction.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 R.id.your_fragment_container是你的两个片段的布局

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在android中将一个片段移动到另一个片段 - How to move one fragment to another fragment in android 如何从一个片段移动到另一个片段? - How to move from one fragment to another fragment? 在Android Studio中,如何使用Java代码将片段切换到另一个片段 - In Android Studio, how do you switch a fragment to another fragment using java code 如何从一个片段移动到另一个片段 - How to move from one fragment to another 如何从Android中的另一个片段调用一个片段方法 - How to call one Fragment Method from another Fragment in android 如何从Android中的另一个片段类调用一个片段的方法 - how to call method of one fragment from another fragment class in android 如何将 object(在这种情况下为 arraylist)从一个片段发送到 java(Android)中的另一个片段 - How to send an object (an arraylist in this situation) from one fragment to another fragment in java (Android) 无法在Android中将一个片段切换到另一个 - Not able to switch one fragment to another in android 如何使用 java 将数据从片段传递到 android 中的另一个片段? - How to pass data from fragment to another fragment in android using java? 如何将bottomnavigationview片段切换到另一个不是菜单项的片段 - How can I switch bottomnavigationview fragment to another one that is not a menu item
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM