为什么在隐藏的片段中调用onResume()?

Apf*_*aft 6 android fragment android-fragments

我的应用在主屏幕上显示了很多图像.用户可以通过触摸图像来查看有关产品的更多信息.主屏幕片段被隐藏,产品细节片段变得可见.通过单击后退键,主屏幕片段将再次可见.

片段转换实现如下:

    @Override
public void showProduct(Product p, boolean isParentTabbed) {
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();

    // the new fragment
    Fragment mFragment = new ProductDetailFragment(p,isParentTabbed);

    //hide main screen fragment and add product detail fragment
    transaction.hide(currentlyOpenedFragment);
    transaction.add(android.R.id.content,mFragment);

    //set new fragment as current "on top" fragment
    currentlyOpenedFragment = mFragment;

    //start animation
    transaction.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top);

    transaction.addToBackStack(null);
    transaction.commit();
}
Run Code Online (Sandbox Code Playgroud)

除非用户在产品详细信息片段中打开共享对话框(标准的android共享意图)并通过单击后退键关闭对话框,否则一切正常.出于某种原因,调用主屏幕片段(隐藏)中的onResume方法.我通过将以下代码添加到主屏幕片段中的onResume方法来解决了这个问题:

    super.onResume();
    if(this.isHidden()){
        Log.d("tab","dont resume tab0fragment because it is hidden");
        return;
    }
Run Code Online (Sandbox Code Playgroud)

这样可以正常工作,但问题仍然存在:当用户关闭其他片段中的共享对话框时,为什么在隐藏片段中调用onResume()?

loa*_*ion 4

隐藏片段仍然遵循片段生命周期。查看文档中的流程图。User navigates backwards or the fragment is removed/replaced.导致onDestroyView()被呼叫,The fragment returns to the layout from the back stack,这是您的主屏幕片段所在的位置。