应用程序应下载数据并将其提供给listFragment obj,但它只对ActionBar下拉列表中的第一个项目“今天”执行此操作。当我选择第二项“很快”应用程序崩溃时出错。
03-21 14:53:05.272: E/AndroidRuntime(5289): FATAL EXCEPTION: main
03-21 14:53:05.272: E/AndroidRuntime(5289): java.lang.IllegalStateException: commit already called
我理解不止一次调用commit()
会产生错误,但屏幕上不显示提交数据。请帮帮我,我不知道怎么解决。任何帮助将不胜感激。
公共类MainActivity扩展了Activity {
ParkFragment mFragment;
ParkFragment mFragment2;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] actions = new String[] {"Today","Soon"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, actions);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (actions[itemPosition] == "Today"){
if (mFragment2 != null){transaction.detach(mFragment2);}
if (mFragment == null){
mFragment = new ParkFragment("url1",MainActivity.this);
transaction.add(android.R.id.content, mFragment);
transaction.commit();
}else{
transaction.attach(mFragment);
transaction.commit();
}
}
if (actions[itemPosition]== "Soon"){
if (mFragment != null){transaction.detach(mFragment);
System.out.println("Detached");}
if (mFragment2 == null){
mFragment2 = new ParkFragment("url2",MainActivity.this);
transaction.add(android.R.id.content, mFragment2);
transaction.commit();
}else{
transaction.attach(mFragment2);
transaction.commit();
}
}
return true;
}
};
actionBar.setListNavigationCallbacks(adapter, navigationListener);
}
答案 0 :(得分:3)
使FragmentTransaction
成为局部变量,而不是成员变量。 PSEUDO:
if (...) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//add.. do stuff
transaction.commit();
} else {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//add.. do stuff
transaction.commit();
}