【问题标题】:Android Fragment not visibleAndroid 片段不可见
【发布时间】:2012-03-10 05:11:47
【问题描述】:

我在我的应用程序中添加了一个后台服务,当有新项目添加到我的应用程序时,它会创建一个通知。当按下通知时,用户被带入应用程序,并且意图传递一个允许应用程序选择新添加的项目的对象。

该应用程序适用于手机和平板电脑。在手机上运行时,项目显示在单独的活动中,在平板电脑上使用双片段布局时,项目显示在右侧片段上。

在主要活动 onCreate 中,我检查意图并检查项目是否已通过,如果已通过则显示它。这在手机上运行良好,但在平板电脑上,正确的片段不可见,因此无法显示该项目。

这就是我在 onCreate 结束时所说的(我在 onStart 和 onResume 中尝试过)

Bundle data = queryIntent.getExtras();
    if  (data!=null){
        Deal deal = data.getParcelable("notificationDeal");
        if (deal!=null){
            onDealSelected(deal);
        }
    }

onDealSeletced 方法执行以下操作

public void onDealSelected(Deal deal) {
    if (!mDualFragments){
        Intent showDealDetails = new Intent(getApplicationContext(), DealDetailsActivity.class);
        showDealDetails.putExtra("Deal", deal);
        showDealDetails.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(showDealDetails);
        Log.d("OnDealSelected", "1");
    }
    else{ // must be tablet
        if (dealDetailsFragment == null)
            dealDetailsFragment = (DealDetailsFragment) getFragmentManager().findFragmentByTag("dealDetailsFragment");
        if (!dealDetailsFragment.isVisible()){
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.right_fragment_container, dealDetailsFragment);
            transaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            transaction.commit();
            getFragmentManager().executePendingTransactions(); // ensure it is done before we call update deal!
            Log.d("OnDealSelected", "2");
        }
        if (dealDetailsFragment.isVisible())    {
            dealDetailsFragment.updateDeal(deal);
            Log.d("OnDealSelected", "3");
        }
    }
}

在智能手机上,mDualFragments 是错误的,因此它会在新活动中显示交易并按预期工作。 当在平板电脑上时,它会进入 else,但是由于片段不可见,它永远不会进入 final if。

在平板电脑上运行应用程序时,它会进入第二个 if 但在它之后片段仍然不可见。

在应用程序的其他点使用相同的方法(当交易未在意图中通过时)并且一直按预期工作。

【问题讨论】:

    标签: android android-intent android-3.0-honeycomb android-fragments android-4.0-ice-cream-sandwich


    【解决方案1】:

    您可以使用setArguments(Bundle bundle) 在附加之前(在提交操作之前)将数据传递给片段。这样,当 Fragment 初始化自身时,它可以调用 getArguments 并解析包。这样你就不必担心片段是否可见,它可以在准备好时创建它的视图。 Fragment中有完整的例子Docs

    【讨论】:

    • 来自文档 - 此处提供的参数将在片段销毁和创建过程中保留。这是否意味着捆绑包会一直保留到应用程序被终止?比如说,用户点击了很多通知,所有的包也会被保留吗?
    • 如果您通过删除或替换事务删除片段,则片段会被销毁(因此捆绑包丢失),但如果您旋转设备并重新附加片段,则捆绑包会保留。每个片段只能调用一次 setArguments,因此要处理多个通知,您只需将旧片段替换为新片段即可。
    • 谢谢。根据您的建议,我已设法使其正常工作。
    【解决方案2】:

    尝试使用 transaction.add() 方法并隐藏前一个片段。我想您的片段现在将可见。

            transaction.add(R.id.right_fragment_container, dealDetailsFragment);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多