Java – how do I add / delete clips on buttons?
•
Java
At present, I have a "relax_layout" container, which I use to add my clips
What I want to achieve is that when I press the button once, the clip should load... When I press it again, the clip should be deleted I have tried to use integers to identify whether fragments are loaded, but failed Any help appreciated
Code:
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(); } }); }
Solution
Your problem is that a new clip is created each time you click the button You need to get a reference to the currently added fragment and delete it
In addition, you no longer need to use this flag When you add a clip, you can mark it After deleting a clip, you can use the tag used to add the clip to get a reference to the currently added clip
Here is an example of how you should do this:
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 ... }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码