Reputation: 333
I want to toggle button to show my fragment when it's clicked on and when I click it again to remove my fragment or hide it. Basically ~ On: Show Off: Hide
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Shower_fragment shower_fragment = new Shower_fragment();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.linear_shower, shower_fragment, "Shower");
if(isChecked){
fragmentTransaction.show(shower_fragment);
fragmentTransaction.commit();
}else{
fragmentTransaction.hide(shower_fragment);
fragmentTransaction.commit();
}
}
Upvotes: 1
Views: 992
Reputation: 333
It works, this way it works. :D ~ Notice the new fragment object in the Else clause.
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Shower_fragment shower_fragment = new Shower_fragment();
android.app.FragmentManager fragmentManager = getFragmentManager();
if( null == fragmentManager){
Toast.makeText(getApplication(), "Null Fragment Manager", Toast.LENGTH_LONG).show();
return;}
if(isChecked){
Toast.makeText(getApplication(),"If Clicked", LENGTH_SHORT).show();
fragmentManager.beginTransaction()
.add(R.id.linear_shower, shower_fragment, "Shower")
.show(shower_fragment)
.commit();
}else{
Toast.makeText(getApplication(), "Else Clicked", LENGTH_SHORT).show();
Shower_fragment shower_fragmentElse = (Shower_fragment) fragmentManager.findFragmentByTag("Shower");
fragmentManager.beginTransaction()
.hide(shower_fragmentElse)
.commit();
}
}
});
By the way, where you put the Override method shouldn't be a problem.
Upvotes: 0
Reputation: 2032
I think your forgot to call getFragmentManager();
Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
Shower_fragment shower_fragment = new Shower_fragment();
FragmentManager fm = getFragmentManager();
if(null == fm){return;}
if(isChecked)
{
fm.beginTransaction();
.add(R.id.linear_shower, shower_fragment, "Shower");
.show()
.commit();
}else
{
fm.beginTransaction();
.add(R.id.linear_shower, shower_fragment, "Shower");
.hide()
.commit();
}
}
Upvotes: 1