Android 开发,使用切换按钮关闭片段
Android development, Closing fragment using toggle button
我认为这个问题可能很简单,但对于 Java 和 Android 开发人员来说还很陌生,我不太确定。我想要做的是关闭一个使用 ToggleButton 切换的片段,但我找不到隐藏或关闭它的方法。任何帮助将不胜感激。
下面是 OnCheckChanged() 侦听器的代码。
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
MyFragment frag = new MyFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.main_activity, frag, "Fragment1");
if(isChecked)
{
transaction.show(frag);
}
else
{
transaction.hide(frag);
//transaction.remove(frag);
}
transaction.commit();
}
每次点击 onCheckedChanged 时,都会添加一个 NEW 片段,然后隐藏或显示它。您之前创建的所有其他片段仍然依附在另一个之上。
如果有的话,您应该获取附加到布局的当前片段。如果还没有,请创建它并将其添加到容器中。
例如,这应该为您指明正确的方向。
private void HideFragment(){
// Get the fragment that is attached to the layout
Fragment frag=getFragmentManager().findFragmentById(R.id.centerFrame);
if (frag==null){
// The fragment does not exist yet so create one and add it
frag=new MyFragment();
getFragmentManager()
.beginTransaction()
.replace(R.id.centerFrame,frag)
.commit();
}
//Hide the fragment
getFragmentManager()
.beginTransaction()
.hide(frag)
.commit();
}
更新:
您实际要达到的目标有点模棱两可。你一直说 "close" 片段,但你的代码表明你只想打开和关闭它的可见性。
如果你真的想完全删除片段,那么你应该使用 FragmentTransaction
的 Remove
方法。
我认为这个问题可能很简单,但对于 Java 和 Android 开发人员来说还很陌生,我不太确定。我想要做的是关闭一个使用 ToggleButton 切换的片段,但我找不到隐藏或关闭它的方法。任何帮助将不胜感激。
下面是 OnCheckChanged() 侦听器的代码。
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
MyFragment frag = new MyFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.main_activity, frag, "Fragment1");
if(isChecked)
{
transaction.show(frag);
}
else
{
transaction.hide(frag);
//transaction.remove(frag);
}
transaction.commit();
}
每次点击 onCheckedChanged 时,都会添加一个 NEW 片段,然后隐藏或显示它。您之前创建的所有其他片段仍然依附在另一个之上。
如果有的话,您应该获取附加到布局的当前片段。如果还没有,请创建它并将其添加到容器中。
例如,这应该为您指明正确的方向。
private void HideFragment(){
// Get the fragment that is attached to the layout
Fragment frag=getFragmentManager().findFragmentById(R.id.centerFrame);
if (frag==null){
// The fragment does not exist yet so create one and add it
frag=new MyFragment();
getFragmentManager()
.beginTransaction()
.replace(R.id.centerFrame,frag)
.commit();
}
//Hide the fragment
getFragmentManager()
.beginTransaction()
.hide(frag)
.commit();
}
更新: 您实际要达到的目标有点模棱两可。你一直说 "close" 片段,但你的代码表明你只想打开和关闭它的可见性。
如果你真的想完全删除片段,那么你应该使用 FragmentTransaction
的 Remove
方法。