Android - searchview with auto complete feature inside action bar

前端 未结 2 1988
迷失自我
迷失自我 2020-12-09 06:51

I want to build an app that has sherlock action bar and a search view inside it. However, i want this searchview to have autocomplete feature like what autocompleteTextView

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 07:24

    I have a simple way to do this without using an autocomplete textview, just put a simple list adapter which contain a ArrayList(itemArrayList) of items, to suggest with search view.Set the adapter to your SearchAutoComplete and auto complete feature will work below is my code.With this, you don't have to use an extra Layout.

     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    
    MenuItem searchItem = menu.findItem(R.id.search);
    SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    
    SearchAutoComplete searchAutoComplete = (SearchAutoComplete)     mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
    searchAutoComplete.setTextColor(Color.WHITE);
    
    ArrayAdapter adapter = new ArrayAdapter(this,
    android.R.layout.simple_dropdown_item_1line, itemArrayList);
    searchAutoComplete.setAdapter(adapter);
    
    SearchManager searchManager =
    (SearchManager) getSystemService(this.SEARCH_SERVICE);
    mSearchView.setSearchableInfo(
    searchManager.getSearchableInfo(getComponentName()));
    return true;
    }
    

    Clicking the suggested item the item should appear on the search view so add the below code just after you set your adapter to searchAutoComplete inside the onCreateOptionmenu(...) method.

    @Override
    public void onItemClick(AdapterView parent, View view, int position,
    long id) {
    // TODO Auto-generated method stub
    
    String searchString=(String)parent.getItemAtPosition(position);
    searchAutoComplete.setText(""+searchString);
    Toast.makeText(MainActivity.this, "you clicked "+searchString, Toast.LENGTH_LONG).show();
    
    }
    });
    

    You can also see the complete code in this Link

提交回复
热议问题