但是它抛出了一个IllegalStateException
Fragment1:
...
mInterstitialAd = new InterstitialAd(this.getContext());
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
masterActivity.showGame(); // <---- here comes the error
}
});
requestNewInterstitial();
// Action Listener on Button show game
Button btnShowGame = (Button) view.findViewById(R.id.btnShowGame);
btnShowGame.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
masterActivity.showGame();
}
return true;
}
});
MasterActivity:
...
public void showGame() {
FragmentGameBoard fragment = new FragmentGameBoard();
fragment.setMasterActivity(this);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();
}
结果如下:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
从这篇文章看来,错误似乎是正常的: http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html
- &GT; &#34;避免在异步回调方法中执行事务。&#34;
但是如何实现我想做的事呢?
这显然与广告和异步逻辑有关。
我不希望用户必须再次点击该按钮来切换片段。
fragment1 -(clickButton)-> interstitialAd -(closeAd)-> fragment1 -(clickButton)-> fragment2
fragment1 -(clickButton)-> interstitialAd -(closeAd)-> fragment2
感谢您的帮助!
答案 0 :(得分:2)
我遇到了同样的问题,并设法解决了以下问题
在showGame()内部更改以下行
而不是:
transaction.commit();
使用:
transaction.commitAllowingStateLoss();