我想切换按钮以在点击时显示我的片段,当我再次单击它以删除我的片段或隐藏它时。 基本上〜开:炫耀:隐藏
@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();
}
}
答案 0 :(得分:0)
我想你忘了调用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();
}
}
答案 1 :(得分:0)
它有效,这种方式有效。 :d 〜注意Else子句中的新片段对象。
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();
}
}
});
顺便说一下,放置Override方法的地方应该不是问题。