2014-11-08 105 views

回答

2

在onCreate中收到的Bundle包含最近提供的数据,如果重新创建活动并且getArguments Bundle返回作为参数提供的bundle。

1

用于创建片段和创建片段的参数集不能再次设置。 onCreate/onCreateView/onActivityCreated/onViewStateRestored中的包是savedInstanceState。你可以使用这个获得通过onSaveInstanceState覆盖保留的持久值。在创建片段时,savedInstanceState包通常为空,因此您可能需要使用getArguments。

有关getArguments的另一件事,你不必坚持这些值。他们将通过fragment code为您重新创建。如果您尝试setArguments上已经有他们一个片段,你会碰到一个IllegalStateException

19

TL; DR:

Fragment.getArguments()是最初创建一个片段。

onCreate(Bundle)用于从前一个实例中检索Bundle。

详细:

我已经冲刷了这个网站,并要求经验丰富的Android开发者,所以这里是一个体面的解释:

的捆绑作为的onCreate参数传递函数用于存在片段的前一个实例,该函数在调用函数时会更新。 (你可以更多关于这个读了这里的官方文档:https://developer.android.com/training/basics/activity-lifecycle/recreating.html

Fragment.getArguments()功能然而,当最初创建片段使用。您将首次导航到片段,并且该片段的前一个实例将不存在。在这种情况下,您可以在使用setArguments()函数getArguments()函数共享的Fragment中设置局部变量。 (更多在这里:https://developer.android.com/reference/android/app/Fragment.html

因此: 健壮的代码看起来是这样的:

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) 
{ 
    super.onCreateView(inflater, container, savedInstanceState); 

    mView = inflater.inflate(R.layout.fragment_name, container, false); 
    mContext = getActivity(); 

    if(savedInstanceState != null){ 
     Log.d("yourapp", "A SavedInstanceState exists, using past values"); 
     mValue = savedInstanceState.getString("valueString"); 
    }else{ 
     Log.d("yourapp", "A SavedInstanceState doesn't exist"); 
     Bundle bundle = getArguments(); 
     mValue = bundle.getString("valueString"); 
    } 
} 

负责处理这两种情况下你的onCreate状态。

希望这会有所帮助!

1

我想加到N15M0_jk的回答。 有时不需要保存片段状态(对于静态片段),并且只能使用进行重新创建,因为即使在破坏之后仍然保留使用setArguments()设置的参数。

查看setArguments()

+0

感谢参考,你已经解决了我的头痛,我不知道为什么是的onSaveInstanceState没用! – Burrich 2017-12-28 12:58:50

相关问题