我真的是android开发的新手。我创建了一个简单的主要活动,并在左上方添加了一个图标。单击它,我可以显示一个空白片段。在屏幕上,它替换了onCreate方法中加载的布局。现在单击另一个图标,我想隐藏该片段并再次加载该布局。怎么做??有帮助吗?
下面是我的代码
//part of oncreate where my layout is loaded
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// part of code when icon clicked and fragment is loaded
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BlankFragment frag = new BlankFragment();
fragmentTransaction.replace(R.id.content_main, frag);
fragmentTransaction.commit();
//another nearby icon clicked
//now i want to replace this fragment from content_main layout
//what code to add??
最佳答案
如果我的问题回答正确,那么我猜这是正确的答案。
//keep track of all fragments you add by tagging
fragmentTransacaction.add(R.id.content, new FragA(), "first");
//and when removeing
Fragment f = getFragmentManager().findFragmentByTag("first");
if(f!=null) fragmentTransac.remove(f);
fragmentTransac.commit();
我来自here