我想在单击 textView 时删除 fragment 并显示 toast。我的代码显示了 toast ,但没有删除 fragment 。
我的方法:
public void hide(View view) {
My_frag myFrag= new My_frag();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.remove(myFrag);
transaction.commit();
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG)
.show();
}
My_frag 类:
public class My_frag extends android.support.v4.app.Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.my_frag_layout, container, false);
}
}
最佳答案
在某些时候您必须创建并添加 Fragment
对吗?您正在 hide(...)
方法中重新创建 fragment ,因此您试图删除从未添加的内容。当然,您可能已经添加了一个 实例,但没有添加您要删除的 实例。
相反,在您的 Activity
中创建一个全局变量 Fragment fragToRemove
。当您创建 fragment 时(即您执行 transaction.add(fragToRemove = new My_Frag);
的地方),您将拥有一个实例。然后将您的 transaction.remove(myFrag)
更改为 transaction.remove(fragToRemove)
它应该可以正常工作。
关于java - 删除 fragment 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11712676/