在哪里设置片段中的工具栏? onCreate() 还是 onStart()?

Where to set-up the toolbar in a fragment? onCreate() or onStart()?

我正在编写一个涉及多个活动的应用程序:每个活动都由更多片段组成。在几乎每个片段中,我都想设置不同的工具栏...我应该在哪里做?我曾经在 onCreate()onCreateView() 中做几乎所有事情,但现在我问自己:也许把它放在 onStart() 中更正确? 我知道 activity 和片段生命周期是如何工作的...但我没有找到 我的具体案例 的答案。 这是我在其中一个片段中使用的代码:

// Toolbar setup
setHasOptionsMenu(true);
AppCompatActivity activity = (AppCompatActivity) getActivity();
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null)
    actionBar.setDisplayHomeAsUpEnabled(true);
    Toolbar tb = (Toolbar) activity.findViewById(R.id.toolbar_main);
    tb.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentManager mng = getFragmentManager();
            mng.popBackStack();
        }
    }); 
if (activity.getSupportActionBar() != null)
    activity.getSupportActionBar().setTitle(R.string.toolbar_title);
    tb.setVisibility(View.VISIBLE);

这是 activity_main.xml 文件的一部分,其中定义了 R.id.toolbar_main

<!--- [...] --->
<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar_main"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!--- [...] --->

好吧,我会建议将工具栏放在您的位置 Activity class。您可以根据需要创建自定义工具栏。在调用片段期间,您可以在 activity 或通过调用方法在片段中进行更改(颜色、主题等)。

在 .onCreate() 方法中执行 - 请参阅 Google 的 Material 设计示例项目:https://github.com/chrisbanes/cheesesquare

在您的 activity 中包含工具栏,并在您的片段中更改颜色、标题等。