java.lang.IllegalStateException: No host
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1184)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1179)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1991)
at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1976)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1041)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
使用Fragment的时候遇到了这个问题,由于我在切换fragment的时候加入了动画效果,当动画正在执行时,用手指滑动(Pad版相册)或者按下遥控器按键(TV版相册)就会crash,出现如上log。
出现这个bug的原因是我将touch事件和onKey事件传递给了Fragment,而这个时候Fragment还在动画状态中,“No host”,没有附着到Activity上面。
因此,解决方法就是在Fragment切换动画时候,标识下这个状态,在这个状态下,Activity的touch事件和onKey事件自己处理即可。
@UiThread
void changeFragment(BaseAlbumFragment targetFragment,
int showAnim, int fadeAnim) {
baseAlbumFragment = targetFragment.newInstance(this);
isFragmentStatOk = false;
fragmentManager
.beginTransaction()
.setCustomAnimations(showAnim, fadeAnim, showAnim,
fadeAnim)
.replace(R.id.album_container, baseAlbumFragment)
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
backStatus();
}
@Background(delay = 2000)
void backStatus(){
isFragmentStatOk = true;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(!isFragmentStatOk){
return true;
}
return super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if(!isFragmentStatOk){
return true;
}
return super.dispatchTouchEvent(ev);
}