android – 更改片段onAdclose.插页式广告

我想在广告关闭后更改片段.

但它抛出了IllegalStateException

片段1:

...
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

– > “避免在异步回调方法中执行事务.”

但是如何实现我想做的呢?

它显然与广告和异步逻辑有关.

我不希望用户必须再次单击该按钮来切换片段.

实际

fragment1 – (clickButton) – > interstitialAd – (closeAd) – > fragment1 – (clickButton) – > fragment2

预期

fragment1 – (clickButton) – > interstitialAd – (closeAd) – > fragment2

谢谢您的帮助 !

最佳答案 我遇到了同样的问题,并设法解决如下问题

在showGame()里面改变了后续行

代替:

器transaction.commit();

使用:

transaction.commitAllowingStateLoss();

点赞