Embedding SearchView in the action bar

I need to create a SearchView from my arrayList<String> and show the suggestions in the dropdown list, same

enter image description here

I am looking for tutorials that explain step by step how to build a SearchView in an action bar.

I also read the documentation after the Google example, but it was not useful to me.

I created a search

 <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/action_search" android:title="Search" android:icon="@android:drawable/ic_menu_search" android:showAsAction="always" android:actionViewClass="android.widget.SearchView" /> </menu>` 

But I do not know how to set the parameters of an array of strings. I tried to get the result in another action, but did not work.

+78
android android-actionbar searchview autocompletetextview
Feb 05 '14 at 18:21
source share
4 answers

It took a while to put together a solution for this, but found that this is the easiest way to make it work the way you describe. There may be better ways to do this, but since you have not posted your activity code, I will have to improvise and assume that you have a list like this at the beginning of your activity:

 private List<String> items = db.getItems(); 

ExampleActivity.java

 private List<String> items; private Menu menu; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.example, menu); this.menu = menu; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView search = (SearchView) menu.findItem(R.id.search).getActionView(); search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); search.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextChange(String query) { loadHistory(query); return true; } }); } return true; } // History @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void loadHistory(String query) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Cursor String[] columns = new String[] { "_id", "text" }; Object[] temp = new Object[] { 0, "default" }; MatrixCursor cursor = new MatrixCursor(columns); for(int i = 0; i < items.size(); i++) { temp[0] = i; temp[1] = items.get(i);replaced s with i as s not used anywhere. cursor.addRow(temp); } // SearchView SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView(); search.setSuggestionsAdapter(new ExampleAdapter(this, cursor, items)); } } 

Now you need to create an adapter extended from CursorAdapter :

ExampleAdapter.java

 public class ExampleAdapter extends CursorAdapter { private List<String> items; private TextView text; public ExampleAdapter(Context context, Cursor cursor, List<String> items) { super(context, cursor, false); this.items = items; } @Override public void bindView(View view, Context context, Cursor cursor) { text.setText(items.get(cursor.getPosition())); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.item, parent, false); text = (TextView) view.findViewById(R.id.text); return view; } } 

This is best done if the list data from the database, you can pass the Cursor returned by the database functions directly to the ExampleAdapter and use the appropriate column selector to display the column text in the TextView that the adapter refers to.

Please note: when importing the CursorAdapter do not import the Android support version; instead, import the standard android.widget.CursorAdapter .

The adapter will also need a custom layout:

Res / Layout / item.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/item" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> 

Now you can customize the list items by adding additional text or graphic presentations to the layout and filling them with data in the adapter.

That should be all, but if you haven't done it yet, you'll need a SearchView menu item:

Res / menu / example.xml

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

Then create a search custom configuration:

Res / xml / searchable.xml

 <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/search" android:hint="@string/search" > </searchable> 

Finally, add this inside the corresponding activity tag in the manifest file:

AndroidManifest.xml

 <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.default_searchable" android:value="com.example.ExampleActivity" /> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> 

Please note: the @string/search used in the examples must be defined in the /strings.xml values, also remember to update the link to com.example for your project.

+122
Mar 10 '14 at 2:06
source share

If someone else has nullptr in the searchview variable, I find that setting the item is a little different:

old:

 android:showAsAction="ifRoom" android:actionViewClass="android.widget.SearchView" 

new:

 app:showAsAction="ifRoom|collapseActionView" app:actionViewClass="androidx.appcompat.widget.SearchView" 

to android x:

 app:showAsAction="ifRoom|collapseActionView" app:actionViewClass="android.support.v7.widget.SearchView" 

For more information, updated documentation is here .

+44
Jan 19 '16 at 15:37
source share



Use Searchview for Searchview

  1. For XML

     <android.support.v7.widget.SearchView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/searchView"> </android.support.v7.widget.SearchView> 



  2. In your fragment or activity

     package com.example.user.salaryin; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.user.salaryin.Adapter.BusinessModuleAdapter; import com.example.user.salaryin.Network.ApiClient; import com.example.user.salaryin.POJO.ProductDetailPojo; import com.example.user.salaryin.Service.ServiceAPI; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class OneFragment extends Fragment implements SearchView.OnQueryTextListener { RecyclerView recyclerView; RecyclerView.LayoutManager layoutManager; ArrayList<ProductDetailPojo> arrayList; BusinessModuleAdapter adapter; private ProgressDialog pDialog; GridLayoutManager gridLayoutManager; SearchView searchView; public OneFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.one_fragment,container,false); pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Please wait..."); searchView=(SearchView)rootView.findViewById(R.id.searchView); searchView.setQueryHint("Search BY Brand"); searchView.setOnQueryTextListener(this); recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); layoutManager = new LinearLayoutManager(this.getActivity()); recyclerView.setLayoutManager(layoutManager); gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2); recyclerView.setLayoutManager(gridLayoutManager); recyclerView.setHasFixedSize(true); getImageData(); // Inflate the layout for this fragment //return inflater.inflate(R.layout.one_fragment, container, false); return rootView; } private void getImageData() { pDialog.show(); ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class); Call<List<ProductDetailPojo>> call = service.getBusinessImage(); call.enqueue(new Callback<List<ProductDetailPojo>>() { @Override public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) { if (response.isSuccessful()) { arrayList = (ArrayList<ProductDetailPojo>) response.body(); adapter = new BusinessModuleAdapter(arrayList, getActivity()); recyclerView.setAdapter(adapter); pDialog.dismiss(); } else if (response.code() == 401) { pDialog.dismiss(); Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) { Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show(); pDialog.dismiss(); } }); } /* @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { getActivity().getMenuInflater().inflate(R.menu.menu_search, menu); MenuItem menuItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem); searchView.setQueryHint("Search Product"); searchView.setOnQueryTextListener(this); }*/ @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { newText = newText.toLowerCase(); ArrayList<ProductDetailPojo> newList = new ArrayList<>(); for (ProductDetailPojo productDetailPojo : arrayList) { String name = productDetailPojo.getDetails().toLowerCase(); if (name.contains(newText) ) newList.add(productDetailPojo); } adapter.setFilter(newList); return true; } } 
  3. In adapter class

      public void setFilter(List<ProductDetailPojo> newList){ arrayList=new ArrayList<>(); arrayList.addAll(newList); notifyDataSetChanged(); } 
+1
Sep 21 '17 at 7:20
source share

SearchDialog or SearchWidget?

When it comes to implementing search functionality, the official documentation for Android developers suggests two approaches .
You can use SearchDialog or SearchWidget .
I am going to explain the implementation of the search function using SearchWidget.

How to do this using a search widget?

I will explain the search functionality in RecyclerView using SearchWidget. It is pretty simple.

Just follow these 5 easy steps

1) Add searchView item to menu

You can add SearchView can be added as actionView in the menu using

app: useActionclass = "android.support.v7.widget.SearchView".

 <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="rohksin.com.searchviewdemo.MainActivity"> <item android:id="@+id/searchBar" app:showAsAction="always" app:actionViewClass="android.support.v7.widget.SearchView" /> </menu> 

2) Customize SerchView tooltip text, listener, etc.

You must initialize the SearchView in onCreateOptionsMenu(Menu menu) .

  @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); MenuItem searchItem = menu.findItem(R.id.searchBar); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setQueryHint("Search People"); searchView.setOnQueryTextListener(this); searchView.setIconified(false); return true; } 

3) Implementation of SearchView.OnQueryTextListener in your activity

OnQueryTextListener has two abstract methods

  1. onQueryTextSubmit(String query)
  2. onQueryTextChange(String newText

So your activity skeleton will look like this

 YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{ public boolean onQueryTextSubmit(String query) public boolean onQueryTextChange(String newText) } 

4) Implementation of SearchView.OnQueryTextListener

You can provide an implementation for abstract methods like this

 public boolean onQueryTextSubmit(String query) { // This method can be used when a query is submitted eg. creating search history using SQLite DB Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show(); return true; } @Override public boolean onQueryTextChange(String newText) { adapter.filter(newText); return true; } 

5) Write a filter method in your RecyclerView adapter.

The most important part is you can write your own logic to perform the search.
Here is my. This snippet shows a list of names that contains text typed in SearchView

 public void filter(String queryText) { list.clear(); if(queryText.isEmpty()) { list.addAll(copyList); } else { for(String name: copyList) { if(name.toLowerCase().contains(queryText.toLowerCase())) { list.add(name); } } } notifyDataSetChanged(); } 

Relevant link:

Full working code in SearchView with SQLite database in this music app

+1
Jan 09 '19 at 11:00
source share



All Articles