【问题标题】:Change fragment onAdclose. Interstitial ad更改片段 onAdclose。插页式广告
【发布时间】:2016-02-25 09:01:13
【问题描述】:

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

但它会抛出一个 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)-&gt; interstitialAd -(closeAd)-&gt; fragment1 -(clickButton)-&gt; fragment2

预期

fragment1 -(clickButton)-&gt; interstitialAd -(closeAd)-&gt; fragment2

感谢您的帮助!

【问题讨论】:

    标签: android asynchronous fragment


    【解决方案1】:

    我遇到了同样的问题,并设法解决它如下

    在 showGame() 中更改跟随行

    代替:

    transaction.commit();

    使用:

    transaction.commitAllowingStateLoss();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      相关资源
      最近更新 更多