我在app中有两个片段。切换它们的代码:
public class MainActivity extends FragmentActivity{
Fragment1 fragment1;
Fragment2 fragment2;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout);
fragment1 = new Fragment1();
fragment2 = new Fragment2();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_vert_add, R.anim.fragment_vert_remove);
fragmentTransaction.add(R.id.linear_layout_id, fragment1);
fragmentTransaction.commit();
}
public void changeFragment() {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_vert_add, R.anim.fragment_vert_remove);
if(fragment1.isAdded())
fragmentTransaction.replace(R.id.linear_layout_id, fragment2);
else
fragmentTransaction.replace(R.id.linear_layout_id, fragment1);
fragmentTransaction.commit();
}
}
在动画期间触摸屏幕时:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: No activity
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1123)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1118)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1927)
at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1800)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:977)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
at dalvik.system.NativeStart.main(Native Method)