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

时间:2013-04-28 11:40:38

标签: android android-fragments fragment

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

片段transacion实现如下:

    @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();
}

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

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

这很好用,但问题仍然存在:当用户关闭另一个片段中的共享对话框时,为什么在隐藏片段中调用onResume()?

1 个答案:

答案 0 :(得分:4)

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