我已经创建了片段隐藏和显示的示例应用程序。第一个片段被正确地添加到视图中。但是在菜单上按下以隐藏片段它没有得到隐藏。我发布了我的代码如下..
public class SwapfragActivity extends Activity
{
FrameLayout fr;
FragmentManager fm = getFragmentManager();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fr = (FrameLayout) findViewById(R.id.fm1);
frag f = new frag();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("SHOW");
menu.add("HIDE");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
frag f = new frag();
if (item.getTitle() == "SHOW")
{
if (!f.isAdded())
{
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fm1, f);
ft.commit();
}
else if (f.isHidden())
{
FragmentTransaction ft = fm.beginTransaction();
ft.show(f);
ft.commit();
}
}
else
{
if (f.isAdded())
{
FragmentTransaction ft = fm.beginTransaction();
ft.hide(f);
ft.commit();
}
}
return true;
}
}
class frag extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.a, container, false);
}
}