简体   繁体   English

在导航抽屉的片段中将操作栏项更改为searchView

[英]Change action bar item to searchView in a fragment of Navigation Drawer

I have a Navigation drawer with fragments. 我有一个带有碎片的导航抽屉。 In all the fragments it shows a share button item in main.xml . 在所有片段中,它在main.xml显示了一个共享按钮项。

The default fragment is PhotoFragment showing share item of main.xml & when IntroductionFragment is clicked in navigation drawer, the action bar then should show searchview item which is in search.xml 默认片段PhotoFragment表示的份额项main.xml &当IntroductionFragment被点击导航抽屉,操作栏然后应该显示搜索查看项目这是在search.xml

MainActivity.java MainActivity.java

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) {
    if(Flag.f==0)
    {
    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);
    }
    else
    {
        getMenuInflater().inflate(R.menu.search, menu);
         // Find the share item
            MenuItem searchItem = menu.findItem(R.id.search);

            // Need to use MenuItemCompat to retrieve the Action Provider
            mActionProvider = (ActionProvider)
                MenuItemCompat.getActionProvider(searchItem);
    // When using the support library, the setOnActionExpandListener() method is
    // static and accepts the MenuItem object as an argument
    MenuItemCompat.setOnActionExpandListener(searchItem, new OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Do something when collapsed
            return true;  // Return true to collapse action view
        }

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            // Do something when expanded
            return true;  // Return true to expand action view
        }
    });
    }
    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);
    if(Flag.f==0)
    menu.findItem(R.id.action_share).setVisible(!drawerOpen);
    else
        menu.findItem(R.id.search).setVisible(!drawerOpen);
    Flag.f=0;
    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);

}
}

This is how I implemented fragment class to get the searchView from search.xml which I am unable to show it in actionbar 这是我实现片段类从search.xml获取searchView的search.xml ,我无法在操作栏中显示它

public class IntroductionFragment extends Fragment{

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

@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.fragment_introduction,container,false);

    ...
    ...

    getActivity().supportInvalidateOptionsMenu();
    return rootView;
} 

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    Log.v("inside onCreateOptionsMenu","???????");
    Flag.f=1;
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.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);

}
}

Search.xml Search.xml

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

</menu>

This is what I tried ! 这就是我试过的!

Using menu.clear() clears the item of main.xml & instead I do not see searchview in IntroductionFragment 使用menu.clear()清除main.xml的项目,而不是在IntroductionFragment中看到searchview

Please identify what should I do to get my desired result. 请确定我应该怎么做以获得我想要的结果。

If you find my question unclear then fell free to comment ! 如果您发现我的问题不清楚,那么可以自由发表评论!

Thanks in advance ! 提前致谢 !

At that line a NullPointerException means the MenuItem with the id R.id.action_share cannot be found. 在该行,NullPointerException意味着无法找到ID为R.id.action_share的MenuItem。 This is normal because your IntroductionFragment, in its onCreateOptionsMenu() method, calls: 这是正常的,因为您的IntroductionFragment在其onCreateOptionsMenu()方法中调用:

menu.clear() 

which will remove all items from the menu(including the previously added main R.id.action_share MenuItem) making the findItem() method to return null. 这将从菜单中删除所有项目(包括以前添加的主要R.id.action_share MenuItem),使findItem()方法返回null。 The solution would be to remove that line menu.clear()(you should explain why are you using clear()). 解决方案是删除该行menu.clear()(你应该解释为什么你使用clear())。

The other option you could do, as I was having the same issue with SearchView (minus the fact that the code is ugly) is to do something like this. 你可以做的另一个选择,因为我遇到与SearchView相同的问题(减去代码丑陋的事实)是做这样的事情。 I have a few patches to update this project later tonight, but it's a good base. 我今晚稍后会有一些补丁来更新这个项目,但这是一个很好的基础。

You basically create an actionLayout with an AutoCompleteTextView or EditText as a search field, and you can manually handle all of the actions necessary for opening and closing dialogs. 您基本上使用AutoCompleteTextView或EditText作为搜索字段创建actionLayout,并且您可以手动处理打开和关闭对话框所需的所有操作。

https://github.com/sinfonianartist/AutoCompleteActionBarDemo https://github.com/sinfonianartist/AutoCompleteActionBarDemo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM