如何删除 activity 布局上的片段
how to remove fragment over an activity layout
我真的是 android 开发的新手。我创建了一个简单的 main activity 并在左上角添加了一个图标。单击它我可以显示空白 fragment.on 我的屏幕替换在 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
那里得到了这个
您可以通过以下代码切换可见性。
public void toggleVisibility(Fragment fragment){
FragmentTransaction transaction = getFragmentManager().beginTransaction();
if (fragment.isHidden()) {
transaction.show(fragment);
} else {
transaction.hide(fragment);
}
transaction.commit();
}
我真的是 android 开发的新手。我创建了一个简单的 main activity 并在左上角添加了一个图标。单击它我可以显示空白 fragment.on 我的屏幕替换在 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
那里得到了这个您可以通过以下代码切换可见性。
public void toggleVisibility(Fragment fragment){
FragmentTransaction transaction = getFragmentManager().beginTransaction();
if (fragment.isHidden()) {
transaction.show(fragment);
} else {
transaction.hide(fragment);
}
transaction.commit();
}