操作栏标题不变

Action bar title doesn't change

我有带导航抽屉的 MainActivity。 这是 MainActivity.java

中的两个函数
    @Override
public void onNavigationDrawerItemSelected(int position) {
    Fragment fragment;
    FragmentManager fragmentManager = getSupportFragmentManager();
    switch(position) {
        default:
        case 0:
            fragment = new AlarmClockFragment().newInstance(position);
            break;
        case 1:
            fragment = new SettingsFragment().newInstance(position);
            break;
    }
    fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}

public void onSectionAttached(int number) {
    switch (number) {
        case 0:
            mTitle = getString(R.string.title_section1);
            break;
        case 1:
            mTitle = getString(R.string.title_section2);
            break;
    }
}

在每个片段中,我都有更改操作栏标题的方法。我是这样做的:

我有:

private static final String ARG_SECTION_NUMBER = "section_number";
private int mSectionNumber = 0;
private OnFragmentInteractionListener mListener;

我得到 ARG_SECTION_NUMBER:

    public static AlarmClockFragment newInstance(int param1) {
    AlarmClockFragment fragment = new AlarmClockFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, param1);
    fragment.setArguments(args);
    return fragment;
}

    @Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
        ((MainActivity) activity).onSectionAttached(mSectionNumber);
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

代码与两个片段(AlarmCLockFragment 和 SettingsFragment)相似,但它不起作用。

如果我不使用变量 mSectionNumber 而只写 ((MainActivity) activity).onSectionAttached(0); 一切都会很好。所以我找不到初始化问题 mSectionNumber.

setTitle() 此处:

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}

片段中的 onCreate():

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
    }
}

为什么不直接让片段设置标题?

onActivityCreated或类似调用中:

((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(...)

编辑:您的具体问题的解决方案是在 Fragment 生命周期中 onAttach 之前调用 onCreate。这里有一个很好的资源可供使用:http://staticfree.info/~steve/complete_android_fragment_lifecycle.png