本文介绍了Android FragmentTransaction 提交已调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的错误:
java.lang.IllegalStateException:提交已经调用
java.lang.IllegalStateException: commit already called
我的代码:
final FragmentTransaction fragmentTransaction =getFragmentManager().beginTransaction();
f1_fragment = new F1_Fragments();
f2_fragment = new F2_Fragments();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position);
if(position==0){
fragmentTransaction.replace(android.R.id.content, f1_fragment);
}else{
fragmentTransaction.replace(android.R.id.content, f2_fragment);
}
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
推荐答案
您正在 OnItemClickListener
之外开始 FragmentTransaction.因此,每次用户单击 ListView 中的项目时,您都尝试 commit()
单个 FragmentTransaction.
You are beginning the FragmentTransaction outside of the OnItemClickListener
. Thus you are attempting to commit()
a single FragmentTransaction every time the user clicks an item in your ListView.
每次您打算执行任意数量的 Fragment 操作时,您都需要开始一个新的 FragmentTransaction.
You need to begin a new FragmentTransaction every time you intend to perform any number of Fragment operations.
一个简单的修复看起来像这样:
A simple fix would look like this:
f1_fragment = new F1_Fragments();
f2_fragment = new F2_Fragments();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction fragmentTransaction =getFragmentManager().beginTransaction();
parent.getItemAtPosition(position);
if(position==0){
fragmentTransaction.replace(android.R.id.content, f1_fragment);
}else{
fragmentTransaction.replace(android.R.id.content, f2_fragment);
}
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
这篇关于Android FragmentTransaction 提交已调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!