在工具栏和动作栏中搜索

时间:2015-03-03 06:09:04

标签: android android-fragments android-toolbar android-search

更新

我正在更新此帖子,以便更容易理解。我刚刚更新了我的应用以使用工具栏与操作栏。我有一个活动MainDrawer2,它包含从导航抽屉加载的所有片段。在顶部,我有一个工具栏,我用这个菜单充气:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">




    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always"
        android:onClick="goToSearch"
        android:title="Search"/>



    <item android:id="@+id/action_barcode"
        android:icon="@drawable/bar"
        android:title="barcode"
        app:showAsAction="ifRoom"
        android:onClick="scanBarcode"/>



</menu>

在上面的菜单中,搜索图标只是一个带有onClick的普通按钮。按下onCLick时,它会加载Search.java:

public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {

    private ListView lv;
    View v;
    SearchView searchView;
    private SearchView mSearchView;
    private MenuItem mSearchMenuItem;
    private Menu optionsMenu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //set layout here
        v = inflater.inflate(R.layout.activity_search, container, false);
        setHasOptionsMenu(true);
        //getActivity().setTitle("Search");


        //get user information
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);


        return v;


    }

    @Override
    public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
        // Inflate the menu; this adds items to the action bar if it is present.

        this.optionsMenu = menu; // HERE

        final MenuItem searchMenuItem = menu.findItem(R.id.action_searchHome);

        //searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);

        searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();


        searchView.setOnQueryTextListener(this);
    }


    public boolean onQueryTextSubmit (String query) {

        //toast query
        //make json variables to fill

        if (optionsMenu != null) {
            //(optionsMenu.findItem(R.id.menu_search2)).collapseActionView();
        }


        // url to make request
        String url = "myURL";



        try {
            query = URLEncoder.encode(query, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        String jsonUrl = url + query;


        //todo: get json
        ReadJSONResult task = new ReadJSONResult(getActivity());
        task.setOnArticleSelectedListener(this);
        task.execute(jsonUrl);

        return false;
    }





    @Override
    public boolean onQueryTextChange(String newText) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onArticleSelected(String b, String brewery){
        searchView.setIconified(true);
        searchView.clearFocus();
        searchView.postInvalidate();
        //code to execute on click
        Fragment Fragment_one;
        FragmentManager man= getFragmentManager();
        FragmentTransaction tran = man.beginTransaction();

        //adds beer data to shared prefs for beer tabs
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        SharedPreferences.Editor editor = preferences.edit();

        editor.putString("beerID",b);
        editor.putString("breweryID",brewery);
        editor.commit();
        Fragment_one = new BeerTabs();

        tran.replace(R.id.main, Fragment_one);//tran.
        tran.addToBackStack(null);
        tran.commit();

    }





}

然后,search.java会膨胀具有可扩展搜索的不同菜单,onCLick也会被应用:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_searchHome"
        android:orderInCategory="100"
        app:showAsAction="never"
        app:actionViewClass="android.support.v7.widget.SearchView"

        android:title="Seach Beer"/>

    <item
        android:id="@+id/action_statisticsHome"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:onClick="goToStatistics"
        android:title="Your Statistics"/>

</menu>

现在,当我尝试使用新的充气菜单打开searchBar时,我收到此错误:

java.lang.NullPointerException
       at com.example.mike.beerportfoliomaterial.Search.onCreateOptionsMenu(Search.java:72)
       at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1868)
       at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1989)
       at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:276)
       at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:276)
       at android.support.v7.app.ActionBarActivityDelegate$1.onCreatePanelMenu(ActionBarActivityDelegate.java:79)
       at android.support.v7.widget.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:49)
       at android.support.v7.internal.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:459)
       at android.support.v7.internal.app.ToolbarActionBar$1.run(ToolbarActionBar.java:69)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:813)
       at android.view.Choreographer.doCallbacks(Choreographer.java:613)
       at android.view.Choreographer.doFrame(Choreographer.java:582)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:799)
       at android.os.Handler.handleCallback(Handler.java:733)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:146)
       at android.app.ActivityThread.main(ActivityThread.java:5653)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
       at dalvik.system.NativeStart.main(NativeStart.java)

第72行是:

    searchView.setOnQueryTextListener(this);

1 个答案:

答案 0 :(得分:0)

你应该:

  1. 将menu.xml android:showAsAction更改为app:showAsAction并添加app:actionViewClass,例如:

    <item
        android:id="@id/search_action"
        android:icon="@drawable/ic_32_white_search"
        android:title="@string/search_action_title"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"
        />
    
  2. 使用setSupportActionBar()将工具栏设置为操作栏(例如onCreate()};

  3. 更改您的onCreateOptionsMenu代码
    searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
    

    final MenuItem searchMenuItem = menu.findItem(R.id.menu_search2);
    searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);