在 Navigation Drawer 的每个片段中实现不同的 Action Bar 项

Posted

技术标签:

【中文标题】在 Navigation Drawer 的每个片段中实现不同的 Action Bar 项【英文标题】:Implement a different Action Bar item in each fragment of Navigation Drawer 【发布时间】:2014-09-18 16:20:26 【问题描述】:

我有一个带有片段的导航抽屉。在所有片段中,它在main.xml 中显示了一个按钮项。

现在,在一些片段中,我想实现 searchview。为此,我在菜单文件夹中创建了search.xml

search.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/search"
    android:title="@string/search_hint"
    android:showAsAction="always"
    android:actionViewClass="android.widget.SearchView" />

</menu>

我需要实施哪些措施来实现这一目标?

提前致谢

更新:MainActivity

public class MainActivity extends ActionBarActivity 
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;


// nav drawer title
private CharSequence mDrawerTitle;

// used to store app title
private CharSequence mTitle;

// slide menu items
private String[] navMenuTitles;

private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    SpannableString s = new SpannableString(getTitle());
    s.setSpan(new TypefaceSpan(this, "BOOKOS.TTF"), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Update the action bar title with the TypefaceSpan instance
    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle(s);


    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

    navDrawerItems = new ArrayList<NavDrawerItem>();


    // adding nav drawer items to array
    // Home
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], 1));
    // Find People
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],1));
    // Photos
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], 1));
    // Communities, Will add a counter here
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], 1));
    // Pages
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], 1));
    // What's hot, We  will add a counter here
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], 1));

    // Recycle the typed array
    //        navMenuIcons.recycle();

    // setting the nav drawer list adapter
    adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
    mDrawerList.setAdapter(adapter);

    // enabling action bar app icon and behaving it as toggle button
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, //nav menu toggle icon
            R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    )
        @SuppressLint("NewApi")
        public void onDrawerClosed(View view) 
            SpannableString s = new SpannableString(mTitle);
            s.setSpan(new TypefaceSpan(getApplicationContext(), "BOOKOS.TTF"), 0, s.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            // Update the action bar title with the TypefaceSpan instance
            ActionBar actionBar = getSupportActionBar();
            actionBar.setTitle(s);
         //   getSupportActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons

            supportInvalidateOptionsMenu();
        

        @SuppressLint("NewApi")
        public void onDrawerOpened(View drawerView) 
            SpannableString s = new SpannableString(mDrawerTitle);
            s.setSpan(new TypefaceSpan(getApplicationContext(), "BOOKOS.TTF"), 0, s.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            // Update the action bar title with the TypefaceSpan instance
            ActionBar actionBar = getSupportActionBar();
            actionBar.setTitle(s);
         //   getSupportActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            supportInvalidateOptionsMenu();
        
    ;
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) 
        // on first time display view for first nav item
      //  displayView(0);
    
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    displayView(7);


/**
 * Slide menu item click listener
 * */
private class SlideMenuClickListener implements
        ListView.OnItemClickListener 
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) 
        // display view for selected nav drawer item
        displayView(position);
    

/**
 * Diplaying fragment view for selected nav drawer list item
 * */
@SuppressLint("NewApi")
private void displayView(int position) 
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) 
    case 0:
        fragment = new IntroductionFragment();
        break;
    case 1:
        fragment = new PrefaceFragment();
        break;
    case 2:
        fragment = new PreambleFragment();
        break;
    case 3:
        fragment = new ContentsFragment();
        break;

    case 4:
        fragment = new SchedulesFragment();
        break;
    case 5:
        fragment = new AppendixFragment();
        break;
    case 6:
        fragment = new AmendmentFragment();
        break;
    case 7:
        fragment = new PhotoFragment();
        break;
    default:
        break;
    

    if (fragment != null) 
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
     else 
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    

ActionProvider mActionProvider;
@Override
public boolean onCreateOptionsMenu(Menu menu) 
    getMenuInflater().inflate(R.menu.main, menu);
 // Find the share item
    MenuItem shareItem = menu.findItem(R.id.action_share);

    // Need to use MenuItemCompat to retrieve the Action Provider
    mActionProvider = (ActionProvider)
        MenuItemCompat.getActionProvider(shareItem);

    return super.onCreateOptionsMenu(menu);



@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // toggle nav drawer on selecting action bar app icon/title
    if (mDrawerToggle.onOptionsItemSelected(item)) 
        return true;
    
    // Handle action bar actions click
    switch (item.getItemId()) 
    case R.id.action_share:
        Intent ints=new Intent(this,ShareActivity.class);

        startActivity(ints);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    


/***
 * Called when invalidateOptionsMenu() is triggered
 */
@Override
public boolean onPrepareOptionsMenu(Menu menu) 
    // if nav drawer is opened, hide the action items
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_share).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);


@SuppressLint("NewApi")
@Override
public void setTitle(CharSequence title) 
    SpannableString s = new SpannableString(mTitle);
    s.setSpan(new TypefaceSpan(this, "BOOKOS.TTF"), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    mTitle = title;
    getSupportActionBar().setTitle(s);


/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 */

@Override
protected void onPostCreate(Bundle savedInstanceState) 
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();


@Override
public void onConfigurationChanged(Configuration newConfig) 
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggls
    mDrawerToggle.onConfigurationChanged(newConfig);



我的片段类

public class IntroductionFragment extends Fragment

public IntroductionFragment()
    setRetainInstance(true); 
    this.setHasOptionsMenu(true);   

 Button b;

 TextView tv1;

@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)

    View rootView = inflater.inflate(R.layout.fragment_introduction,container,false);
    SpannableString s = new SpannableString("Introduction");
    s.setSpan(new TypefaceSpan(getActivity(), "BOOKOS.TTF"), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "BOOKOS.TTF");

     tv1 = (TextView)rootView.findViewById(R.id.textView1);
    tv1.setTypeface(typeface);

    getActivity().supportInvalidateOptionsMenu();
    return rootView;
 




@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
    Log.v("inside onCreateOptionsMenu","???????");
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    getActivity().getMenuInflater().inflate(R.menu.search, menu);









@Override
public void onConfigurationChanged(Configuration newConfig) 

    super.onConfigurationChanged(newConfig);
    LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.fragment_introduction, null);
    ViewGroup rootView = (ViewGroup) getView();
    rootView.removeAllViews();
    rootView.addView(view);



这是日志

07-27 17:27:16.200: V/inside onCreateOptionsMenu(19875): ???????
07-27 17:27:16.210: W/dalvikvm(19875): threadid=1: thread exiting with uncaught exception (group=0x40d98450)
07-27 17:27:16.280: E/AndroidRuntime(19875): FATAL EXCEPTION: main
07-27 17:27:16.280: E/AndroidRuntime(19875): java.lang.NullPointerException
07-27 17:27:16.280: E/AndroidRuntime(19875):    at com.vivekwarde.indianconstitution.MainActivity.onPrepareOptionsMenu(MainActivity.java:244)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.app.Activity.onPreparePanel(Activity.java:2494)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.FragmentActivity.onPrepareOptionsPanel(FragmentActivity.java:491)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivity.superOnPrepareOptionsPanel(ActionBarActivity.java:240)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivityDelegate.onPrepareOptionsPanel(ActionBarActivityDelegate.java:160)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivity.onPrepareOptionsPanel(ActionBarActivity.java:212)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:480)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:236)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivityDelegateICS.onPreparePanel(ActionBarActivityDelegateICS.java:155)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivity.onPreparePanel(ActionBarActivity.java:204)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onPreparePanel(ActionBarActivityDelegateICS.java:290)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:425)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:751)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.app.Activity.invalidateOptionsMenu(Activity.java:2595)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.ActivityCompatHoneycomb.invalidateOptionsMenu(ActivityCompatHoneycomb.java:29)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.FragmentActivity.supportInvalidateOptionsMenu(FragmentActivity.java:648)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v7.app.ActionBarActivity.supportInvalidateOptionsMenu(ActionBarActivity.java:170)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at com.vivekwarde.indianconstitution.IntroductionFragment.onCreateView(IntroductionFragment.java:48)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.os.Handler.handleCallback(Handler.java:615)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.os.Looper.loop(Looper.java:137)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at android.app.ActivityThread.main(ActivityThread.java:4794)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at java.lang.reflect.Method.invokeNative(Native Method)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at java.lang.reflect.Method.invoke(Method.java:511)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
07-27 17:27:16.280: E/AndroidRuntime(19875):    at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

【参考方案1】:

对于每个需要有菜单的片段:

在构造函数中调用this.setHasOptionsMenu(true)。 实现onCreateOptionsMenu(..)onOptionsItemSelected(..) 来处理该片段的菜单项。

在抽屉布局中:

每当您切换片段时,请在您的活动上调用invalidateOptionsMenu()

如果您使用 support-v4 片段,请致电 supportInvalidateOptionsMenu()。 Android 版本在处理这些内容方面存在一些差异,因此请确保您分别在 Ice Cream Sandwich、Jelly Bean 和 KitKat 上进行测试。

【讨论】:

谢谢,我按照你说的修改了我的片段类,但是在实现你的 ans 之后,我在onPrepareOptionsMenu 中得到了空指针异常。我也很困惑在哪里打电话supportInvalidateOptionsMenu()。看看我的编辑,希望你能找出我的错误 可能是这个位:getActivity().getMenuInflater().inflate(R.menu.search, menu);,你应该用inflater.inflate(R.menu.search, menu);替换它。 如果你不发布异常堆栈跟踪,那么尝试调试它就没有什么意义了。 好的,现在跟随最顶层的堆栈帧到 MainActivity 的第 244 行。查看该行代码并查看该代码行上的哪些引用可能导致空指针异常。如果需要,添加空检查或以其他方式更改代码以避免取消引用空引用。 感谢在 onPrepareOptionsMenu 中为片段提供 if 条件和膨胀菜单

以上是关于在 Navigation Drawer 的每个片段中实现不同的 Action Bar 项的主要内容,如果未能解决你的问题,请参考以下文章

Android Drawer - 使用 Navigation.findNavController() 导航到多个片段

java 导航抽屉切换活动而不是片段。字体:https://stackoverflow.com/questions/19442378/navigation-drawer-to-switch-

Android Navigation Drawer Show Up Indicator for Lower Level Fragments

v-navigation-drawer 在窗口调整大小时掉入失控循环

向@react-navigation/drawer 组件发送道具

VueJs - Vuetify - v-navigation-drawer 与智能手机的迷你变体