操作栏标题不会更改

时间:2015-01-29 15:44:23

标签: android android-actionbar

我有使用导航抽屉的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);
    }
}

1 个答案:

答案 0 :(得分:1)

为什么不让Fragments设置标题?

onActivityCreated或类似的电话中:

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

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