目前我有一个“RELATIVE_LAYOUT”容器,我用它来添加我的片段.
我在按钮上使用OnClickListener将片段 XML布局加载到RelativeLayout容器中.
我在按钮上使用OnClickListener将片段 XML布局加载到RelativeLayout容器中.
我想要实现的是,当我按下按钮一次时,片段应该加载……当我再次按下它时,应该删除片段.我已经尝试使用整数来识别是否加载了片段,但是失败了.
任何帮助赞赏……
码:
public class MainActivity extends Activity { Button B1,B2; int boolb1=0,boolb2=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); B1 = (Button)findViewById(R.id.btn1); B2 = (Button)findViewById(R.id.btn2); B1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); FragmentOne f1 = new FragmentOne(); if(boolb1==0) {ft.add(R.id.frg1,f1); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); boolb1=1;} else {ft.remove(f1); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); boolb1=0;} //ft.addToBackStack("f1"); ft.commit(); } }); B2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); FragmentTwo f2 = new FragmentTwo(); if(boolb2==0) { ft.add(R.id.frg2,f2); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); boolb2=1; } else { ft.remove(f2); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); boolb2=0; } //ft.addToBackStack("f2"); ft.commit(); } }); }
解决方法
您的问题是每次单击按钮时都会创建一个新的片段.您需要获取对当前添加的Fragment的引用,然后删除该片段.
此外,您不再需要使用该标志.
添加片段时,您可以标记它.删除片段后,您可以使用用于添加片段的标记来获取对当前添加的片段的引用.
以下是您应该如何执行此操作的示例:
private Button B1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); B1 = (Button)findViewById(R.id.btn1); B1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); FragmentOne f = (FragmentOne) fm.findFragmentByTag("tag"); if(f == null) { // not added f = new FragmentOne(); ft.add(R.id.frg1,f,"tag"); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); } else { // already added ft.remove(f); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); } ft.commit(); } }); // and so on ... }