IllegalStateException:使用ViewPager在onSaveInstanceState之后无法执行此操作

问题描述 投票:438回答:32

我从我的应用程序中获取用户报告,提供以下异常:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1109)
at android.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:399)
at android.app.Activity.onBackPressed(Activity.java:2066)
at android.app.Activity.onKeyUp(Activity.java:2044)
at android.view.KeyEvent.dispatch(KeyEvent.java:2529)
at android.app.Activity.dispatchKeyEvent(Activity.java:2274)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1855)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1277)
at android.app.Activity.dispatchKeyEvent(Activity.java:2269)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.widget.TabHost.dispatchKeyEvent(TabHost.java:297)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1855)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1277)
at android.app.Activity.dispatchKeyEvent(Activity.java:2269)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803)
at android.view.ViewRoot.deliverKeyEventPostIme(ViewRoot.java:2880)
at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2853)
at android.view.ViewRoot.handleMessage(ViewRoot.java:2028)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4028)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)

显然它与FragmentManager有关,我不使用它。 stacktrace没有显示我自己的任何类,所以我不知道这个异常发生在哪里以及如何防止它。

对于记录:我有一个tabhost,并且在每个选项卡中都有一个ActivityGroup在Activities之间切换。

android android-fragments android-viewpager illegalstateexception fragmenttransaction
32个回答
684
投票

请检查我的答案here。基本上我只需要:

@Override
protected void onSaveInstanceState(Bundle outState) {
    //No call for super(). Bug on API Level > 11.
}

不要在super()方法上调用saveInstanceState。这搞砸了......

这是支持包中已知的bug

如果您需要保存实例并向outState Bundle添加内容,则可以使用以下内容:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
    super.onSaveInstanceState(outState);
}

最后,正确的解决方案(如评论中所示)使用:

transaction.commitAllowingStateLoss();

当添加或执行导致FragmentTransactionException时。


5
投票

我有类似的问题,场景是这样的:

  • 我的活动是添加/替换列表片段。
  • 每个列表片段都有对活动的引用,以便在单击列表项时通知活动(观察者模式)。
  • 每个列表片段调用setRetainInstance(true);在其onCreate方法中。

活动的onCreate方法是这样的:

mMainFragment = (SelectionFragment) getSupportFragmentManager()
                .findFragmentByTag(MAIN_FRAGMENT_TAG);
        if (mMainFragment == null) {
            mMainFragment = new SelectionFragment();

            mMainFragment.setListAdapter(new ArrayAdapter<String>(this,
                    R.layout.item_main_menu, getResources().getStringArray(
                            R.array.main_menu)));
mMainFragment.setOnSelectionChangedListener(this);
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction();
            transaction.add(R.id.content, mMainFragment, MAIN_FRAGMENT_TAG);
            transaction.commit();
        }

抛出异常是因为when配置更改(设备已旋转),活动已创建,主片段从片段管理器的历史记录中检索,同时片段已经具有对已销毁活动的OLD引用

将实现更改为此解决了问题:

mMainFragment = (SelectionFragment) getSupportFragmentManager()
                .findFragmentByTag(MAIN_FRAGMENT_TAG);
        if (mMainFragment == null) {
            mMainFragment = new SelectionFragment();

            mMainFragment.setListAdapter(new ArrayAdapter<String>(this,
                    R.layout.item_main_menu, getResources().getStringArray(
                            R.array.main_menu)));
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction();
            transaction.add(R.id.content, mMainFragment, MAIN_FRAGMENT_TAG);
            transaction.commit();
        }
        mMainFragment.setOnSelectionChangedListener(this);

您需要在每次创建活动时设置侦听器,以避免碎片引用旧的已销毁活动实例的情况。


3
投票

当我按下按钮取消我的地图片段活动上的意图选择器时,我得到了这个例外。我通过将onResume(我正在初始化片段)的代码替换为onstart()来解决这个问题,并且应用程序工作正常。希望它有所帮助。


2
投票

我认为使用transaction.commitAllowingStateLoss();不是最好的解决方案。当活动的配置发生变化并调用片段onSavedInstanceState(),然后您的异步回调方法尝试提交片段时,将抛出此异常。

简单的解决方案可以检查活动是否正在改变配置

例如检查isChangingConfigurations()

if(!isChangingConfigurations()) { //commit transaction. }

结帐this链接也是如此


2
投票

如果你在onActivityResult中做了一些FragmentTransaction,你可以在onActivityResult中设置一些布尔值,然后在onResume中你可以根据布尔值进行FragmentTransaction。请参考下面的代码。

@Override
protected void onResume() {
    super.onResume;
    if(isSwitchFragment){
        isSwitchFragment=false;
        bottomNavigationView.getTabAt(POS_FEED).select();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == FilterActivity.FILTER_REQUEST_EVENT && data != null) {
        isSwitchFragment=true;
    }
}

2
投票

如果从FragmentActivity继承,则必须在onActivityResult()中调用超类:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    ...
}

如果你不这样做并尝试在该方法中显示片段对话框,你可能会获得OP的IllegalStateException。 (老实说,我不太明白为什么超级调用解决了这个问题.onActivityResult()onResume()之前被调用,所以它仍然不允许显示片段对话框。)


1
投票

从支持库版本24.0.0开始,您可以调用FragmentTransaction.commitNow()方法,该方法同步提交此事务,而不是调用commit(),然后调用executePendingTransactions()。正如documentation所说,这种方法更好:

调用commitNow比调用commit()后跟executePendingTransactions()更好,因为后者会产生副作用,即尝试提交所有当前挂起的事务,无论这是否是所需的行为。


1
投票

可能我在我的案例中找到的最顺畅和最简单的解决方案是避免在响应活动结果时将有问题的片段弹出堆栈。所以在我的onActivityResult()中更改此调用:

popMyFragmentAndMoveOn();

对此:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        popMyFragmentAndMoveOn();
    }
}

帮助我的情况。


1
投票

每当您尝试在活动中加载片段时,请确保活动处于恢复状态且不会暂停状态。在暂停状态下,您可能最终会丢失已完成的提交操作。

您可以使用transaction.commitAllowingStateLoss()而不是transaction.commit()来加载片段

要么

创建一个布尔值并检查活动是否不会暂停

@Override
public void onResume() {
    super.onResume();
    mIsResumed = true;
}

@Override
public void onPause() {
    mIsResumed = false;
    super.onPause();
}

然后加载片段检查

if(mIsResumed){
//load the your fragment
}

1
投票

为了绕过这个问题,我们可以使用在Google I / O 2018中引入的The Navigation Architecture Component。导航架构组件简化了Android应用程序中导航的实现。


1
投票

礼貌:Solution for IllegalStateException

这个问题困扰了我很多时间,但幸运的是我带来了一个具体的解决方案。它的详细解释是here

使用commitAllowStateloss()可能会阻止此异常,但会导致UI不规则。到目前为止,我们已经理解当我们尝试在Activity状态丢失后提交片段时遇到IllegalStateException - 所以我们应该只延迟事务直到状态恢复这可以简单地完成

声明两个私有布尔变量

 public class MainActivity extends AppCompatActivity {

    //Boolean variable to mark if the transaction is safe
    private boolean isTransactionSafe;

    //Boolean variable to mark if there is any transaction pending
    private boolean isTransactionPending;

现在在onPostResume()和onPause中我们设置并取消设置我们的布尔变量isTransactionSafe。想法是仅在活动处于前景时标记trasnsaction安全,因此不存在状态损失的可能性。

/*
onPostResume is called only when the activity's state is completely restored. In this we will
set our boolean variable to true. Indicating that transaction is safe now
 */
public void onPostResume(){
    super.onPostResume();
    isTransactionSafe=true;
}
/*
onPause is called just before the activity moves to background and also before onSaveInstanceState. In this
we will mark the transaction as unsafe
 */

public void onPause(){
    super.onPause();
    isTransactionSafe=false;

}

private void commitFragment(){
    if(isTransactionSafe) {
        MyFragment myFragment = new MyFragment();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frame, myFragment);
        fragmentTransaction.commit();
    }
}

- 我们到目前为止所做的将从IllegalStateException中保存,但是如果它们在活动转移到后台后完成,那么我们的事务就会丢失,有点像commitAllowStateloss()。为了帮助我们,我们有isTransactionPending布尔变量

public void onPostResume(){
   super.onPostResume();
   isTransactionSafe=true;
/* Here after the activity is restored we check if there is any transaction pending from
the last restoration
*/
   if (isTransactionPending) {
      commitFragment();
   }
}


private void commitFragment(){

 if(isTransactionSafe) {
     MyFragment myFragment = new MyFragment();
     FragmentManager fragmentManager = getFragmentManager();
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
     fragmentTransaction.add(R.id.frame, myFragment);
     fragmentTransaction.commit();
     isTransactionPending=false;
 }else {
     /*
     If any transaction is not done because the activity is in background. We set the
     isTransactionPending variable to true so that we can pick this up when we come back to
foreground
     */
     isTransactionPending=true;
 }
}

116
投票

类似的错误消息存在许多相关问题。检查此特定堆栈跟踪的第二行。此异常与FragmentManagerImpl.popBackStackImmediate的调用特别相关。

如果已保存会话状态,则此方法调用(如popBackStack)将始终使用IllegalStateException失败。检查来源。没有什么可以阻止抛出此异常。

  • 删除对super.onSaveInstanceState的调用无济于事。
  • 使用commitAllowingStateLoss创建片段无济于事。

以下是我观察问题的方法:

  • 有一个带有提交按钮的表单。
  • 单击该按钮时,将创建一个对话框并启动异步过程。
  • 用户在过程完成之前单击主页键 - 调用onSaveInstanceState
  • 该过程完成,进行回调并尝试popBackStackImmediate
  • IllegalStateException被抛出。

这就是我为解决它而做的事情:

因为在回调中无法避免IllegalStateException,所以请抓住并忽略它。

try {
    activity.getSupportFragmentManager().popBackStackImmediate(name);
} catch (IllegalStateException ignored) {
    // There's no way to avoid getting this if saveInstanceState has already been called.
}

这足以阻止应用程序崩溃。但现在用户将恢复应用程序并看到他们认为按下的按钮根本没有被按下(他们认为)。表单片段仍在显示!

要解决此问题,请在创建对话框时,进行一些状态以指示进程已启动。

progressDialog.show(fragmentManager, TAG);
submitPressed = true;

并将此状态保存在捆绑中。

@Override
public void onSaveInstanceState(Bundle outState) {
    ...
    outState.putBoolean(SUBMIT_PRESSED, submitPressed);
}

别忘了在onViewCreated再次加载它

然后,在恢复时,如果先前尝试过提交,则回滚片段。这可以防止用户回到看似未提交的表单。

@Override
public void onResume() {
    super.onResume();
    if (submitPressed) {
        // no need to try-catch this, because we are not in a callback
        activity.getSupportFragmentManager().popBackStackImmediate(name);
        submitPressed = false;
    }
}

1
投票

关于@Anthonyeef很好的答案,这是Java中的示例代码:

private boolean shouldShowFragmentInOnResume;

private void someMethodThatShowsTheFragment() {

    if (this.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
        showFragment();
    } else {
        shouldShowFragmentInOnResume = true;
    }
}

private void showFragment() {
    //Your code here
}

@Override
protected void onResume() {
    super.onResume();

    if (shouldShowFragmentInOnResume) {
        shouldShowFragmentInOnResume = false;
        showFragment();
    }
}

1
投票

在我的情况下,我在名为onActivityResult的覆盖方法中得到此错误。在挖掘之后,我只想弄清楚我之前需要打电话给'超级'。 我添加它,它只是工作

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data); //<--- THIS IS THE SUPPER CALL
    if (resultCode == Activity.RESULT_OK && requestCode == 0) {
        mostrarFragment(FiltroFragment.newInstance())
    }

}

也许您只需要在代码之前的任何覆盖上添加“超级”。


0
投票

在您的活动中添加此内容

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (outState.isEmpty()) {
        // Work-around for a pre-Android 4.2 bug
        outState.putBoolean("bug:fix", true);
    }
}

0
投票

我也经历过这个问题,每当你的FragmentActivity的上下文发生变化时就会出现问题(例如屏幕方向改变等)。所以最好的解决方法是从你的FragmentActivity更新上下文。


0
投票

我最终创建了一个基本片段,并在我的应用程序中使所有片段扩展它

public class BaseFragment extends Fragment {

    private boolean mStateSaved;

    @CallSuper
    @Override
    public void onSaveInstanceState(Bundle outState) {
        mStateSaved = true;
        super.onSaveInstanceState(outState);
    }

    /**
     * Version of {@link #show(FragmentManager, String)} that no-ops when an IllegalStateException
     * would otherwise occur.
     */
    public void showAllowingStateLoss(FragmentManager manager, String tag) {
        // API 26 added this convenient method
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (manager.isStateSaved()) {
                return;
            }
        }

        if (mStateSaved) {
            return;
        }

        show(manager, tag);
    }
}

然后,当我尝试显示片段时,我使用showAllowingStateLoss而不是show

像这样:

MyFragment.newInstance()
.showAllowingStateLoss(getFragmentManager(), MY_FRAGMENT.TAG);

我从这个PR来到这个解决方案:https://github.com/googlesamples/easypermissions/pull/170/files


0
投票

另一种可能的解决方法,我不确定在所有情况下是否有帮助(来源here):

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final View rootView = findViewById(android.R.id.content);
        if (rootView != null) {
            rootView.cancelPendingInputEvents();
        }
    }
}

0
投票

我知道@Ovidiu Latcu已经接受了答案,但过了一段时间,错误仍然存​​在。

@Override
protected void onSaveInstanceState(Bundle outState) {
     //No call for super(). Bug on API Level > 11.
}

Crashlytics仍然向我发送这个奇怪的错误消息。

但是现在仅在版本7+(Nougat)上发生错误我的修复是在fragmentTransaction中使用commitAllowingStateLoss()而不是commit()。

这个post对commitAllowingStateLoss()有帮助,并且从未再次出现过片段问题。

总结一下,这里接受的答案可能适用于前Nougat Android版本。

这可能会节省一些人的搜索时间。快乐的编码。 <3欢呼


0
投票

我有同样的问题。这是因为以前的活动遭到破坏。当ı支持之前的活动时,它被销毁了。我把它作为基础活动(错误)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SpinnerCustom2.setFragmentManager(getSupportFragmentManager());
    onCreateDrawerActivity(savedInstanceState);
}

我把它放在onStart它是正确的

@Override
protected void onStart() {
    super.onStart();
    SpinnerCustom2.setFragmentManager(getSupportFragmentManager());

}

0
投票

抛出此异常(在FragmentActivity中):

@Override
public void onBackPressed() {
    if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) {
        super.onBackPressed();
    }
}

FragmentManager.popBackStatckImmediate()FragmentManager.checkStateLoss()首先被称为。这是IllegalStateException的原因。请参阅以下实施:

private void checkStateLoss() {
    if (mStateSaved) { // Boom!
        throw new IllegalStateException(
                "Can not perform this action after onSaveInstanceState");
    }
    if (mNoTransactionsBecause != null) {
        throw new IllegalStateException(
                "Can not perform this action inside of " + mNoTransactionsBecause);
    }
}

我只需使用标记来标记Activity的当前状态即可解决此问题。这是我的解决方案:

public class MainActivity extends AppCompatActivity {
    /**
     * A flag that marks whether current Activity has saved its instance state
     */
    private boolean mHasSaveInstanceState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mHasSaveInstanceState = true;
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHasSaveInstanceState = false;
    }

    @Override
    public void onBackPressed() {
        if (!mHasSaveInstanceState) {
            // avoid FragmentManager.checkStateLoss()'s throwing IllegalStateException
            super.onBackPressed();
        }
    }
}

0
投票

如果您使用popBackStack()或popBackStackImmediate()方法崩溃,请尝试使用以下方法:

        if (!fragmentManager.isStateSaved()) {
            fragmentManager.popBackStackImmediate();
        }

这对我也有用。


53
投票

在显示片段之前检查活动isFinishing()并注意commitAllowingStateLoss()

例:

if(!isFinishing()) {
FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            DummyFragment dummyFragment = DummyFragment.newInstance();
            ft.add(R.id.dummy_fragment_layout, dummyFragment);
            ft.commitAllowingStateLoss();
}

0
投票

@Gian Gomen在我的情况下,调用SUPER解决了问题。这似乎是更正确的解决方案然后commitAllowingStateLoss(),因为它解决了问题,而不是隐藏它。

@Override
public void onRequestPermissionsResult(
     final int requestCode,
     @NonNull final String[] permissions, 
     @NonNull final int[] grantResults
) {
        super.onRequestPermissionsResult(requestCode,permissions, grantResults); //<--- Without this line crash 
        switch (requestCode) {
            case Constants.REQUEST_CODE_PERMISSION_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onPermissionGranted(Constants.REQUEST_CODE_PERMISSION_STORAGE);
                }
                break;
        }


21
投票

以下是此问题的不同解决方案。

使用私有成员变量,您可以将返回的数据设置为intent,然后可以在super.onResume()之后处理;

像这样:

private Intent mOnActivityResultIntent = null; 

@Override
protected void onResume() {
    super.onResume();
    if(mOnActivityResultIntent != null){
        ... do things ...
        mOnActivityResultIntent = null;
    }
 }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(data != null){
        mOnActivityResultIntent = data;
    }
}

21
投票

这是2017年10月,谷歌使用新的东西调用生命周期组件制作Android支持库。它为此问题提供了一些新的想法'在onSaveInstanceState之后无法执行此操作'问题。

简而言之:

  • 使用生命周期组件来确定弹出片段的正确时间。

更长版本说明:

  • 为什么这个问题出来了? 这是因为你试图从你的活动中使用FragmentManager(我想要保留你的片段?)为你的片段提交一个事务。通常这看起来就像你正在尝试为即将到来的片段做一些事务,同时主机活动已经调用savedInstanceState方法(用户可能碰巧触摸主页按钮,所以活动调用onStop(),在我的情况下,这是原因) 通常这个问题不应该发生 - 我们总是尝试在最开始时将片段加载到活动中,就像onCreate()方法是一个完美的地方。但有时会发生这种情况,特别是当您无法确定要加载到该活动的片段时,或者您正在尝试从AsyncTask块加载片段(或者任何事情需要一些时间)。在片段事务真正发生之前的时间,但在活动的onCreate()方法之后,用户可以做任何事情。如果用户按下主页按钮,触发活动的onSavedInstanceState()方法,将会有can not perform this action崩溃。 如果有人想在这个问题上看得更深,我建议他们看看这个博客post。它深入了解源代码层并对其进行了大量解释。此外,它给出了你不应该使用commitAllowingStateLoss()方法来解决此崩溃的原因(相信我它对你的代码没有任何好处)
  • 如何解决这个问题? 我应该使用commitAllowingStateLoss()方法加载片段吗?不,你不应该; 我应该覆盖onSaveInstanceState方法,忽略它内部的super方法吗?不,你不应该; 我应该使用神奇的isFinishing内部活动,检查主机活动是否在片段交易的正确时刻?是的,这看起来是正确的方法。
  • 看看Lifecycle组件可以做什么。 基本上,Google在AppCompatActivity类(以及您应该在项目中使用的其他几个基类)中进行了一些实现,这使得更容易确定当前的生命周期状态。回顾一下我们的问题:为什么会出现这个问题?这是因为我们在错误的时间做某事。所以我们尽量不这样做,这个问题就会消失。 我为自己的项目编写了一些代码,这是我使用LifeCycle做的。我在Kotlin编码。
val hostActivity: AppCompatActivity? = null // the activity to host fragments. It's value should be properly initialized.

fun dispatchFragment(frag: Fragment) {
    hostActivity?.let {
       if(it.lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED)){
           showFragment(frag)
       }
    }
}

private fun showFragment(frag: Fragment) {
    hostActivity?.let {
        Transaction.begin(it, R.id.frag_container)
                .show(frag)
                .commit()
    }

正如我在上面所示。我将检查主机活动的生命周期状态。借助支持库中的Lifecycle组件,这可能更具体。代码lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED)的意思是,如果当前状态至少是onResume,不迟于它?这确保我的方法不会在其他生命状态(如onStop)中执行。

  • 一切都完成了吗? 当然不是。我展示的代码告诉了一些防止应用程序崩溃的新方法。但是,如果它确实进入onStop的状态,那行代码将不会做任何事情,因此在屏幕上不显示任何内容。当用户返回应用程序时,他们将看到一个空屏幕,这是空主机活动,根本没有显示任何片段。这是糟糕的经历(是的,比崩溃好一点)。 所以在这里我希望有更好的东西:如果生命状态晚于onResume,应用程序不会崩溃,事务方法是生命状态感知;此外,在用户回到我们的应用程序之后,活动将尝试继续完成该片段事务操作。 我在这个方法中添加了更多内容:
class FragmentDispatcher(_host: FragmentActivity) : LifecycleObserver {
    private val hostActivity: FragmentActivity? = _host
    private val lifeCycle: Lifecycle? = _host.lifecycle
    private val profilePendingList = mutableListOf<BaseFragment>()

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume() {
        if (profilePendingList.isNotEmpty()) {
            showFragment(profilePendingList.last())
        }
    }

    fun dispatcherFragment(frag: BaseFragment) {
        if (lifeCycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) == true) {
            showFragment(frag)
        } else {
            profilePendingList.clear()
            profilePendingList.add(frag)
        }
    }

    private fun showFragment(frag: BaseFragment) {
        hostActivity?.let {
            Transaction.begin(it, R.id.frag_container)
                    .show(frag)
                    .commit()
        }
    }
}

我在这个dispatcher类中维护一个列表,以存储那些没有机会完成事务操作的片段。当用户从主屏幕返回并发现仍有片段等待启动时​​,它将转到resume()注释下的@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)方法。现在我认为它应该像我预期的那样工作。


18
投票

短而有效的解决方案:

遵循简单步骤

脚步

步骤1:在相应的片段中覆盖onSaveInstanceState状态。并从中删除超级方法。

 @Override
public void onSaveInstanceState( Bundle outState ) {

}  

第2步:使用fragmentTransaction.commitAllowingStateLoss( );

片段操作时代替fragmentTransaction.commit( );


12
投票

请注意,使用transaction.commitAllowingStateLoss()可能会给用户带来糟糕的体验。有关抛出此异常的原因的详细信息,请参阅this post


10
投票

我找到了解决这类问题的肮脏方案。如果你仍然想出于任何原因保留你的ActivityGroups(我有时间限制的原因),你只需要实现

public void onBackPressed() {}

在你的Activity并在那里做一些back代码。即使旧设备上没有这样的方法,这个方法也会被更新的方法调用。


6
投票

不要使用commitAllowingStateLoss(),它只应用于UI状态可以在用户上意外更改的情况。

https://developer.android.com/reference/android/app/FragmentTransaction.html#commitAllowingStateLoss()

如果事务发生在parentFragment的ChildFragmentManager中,请使用parentFragment.isResume()outside来检查。

if (parentFragment.isResume()) {
    DummyFragment dummyFragment = DummyFragment.newInstance();
    transaction = childFragmentManager.BeginTransaction();
    trans.Replace(Resource.Id.fragmentContainer, startFragment);
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.