[英]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.setOnCheckedChangeListener
和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 R.id.your_fragment_container
是你的两个片段的布局
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.