Search code examples
androidsearchview

Search autocomplete android


I am fresh to android and i was asked to build a search with autocomplete like in this figure enter image description here

I tried SearchAutoComplete in android.support.v7.widget.searchview but i can't get the desired result so any help this is what i tried

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.main_menu,menu);
    MenuItem searchItem = menu.findItem(R.id.app_bar_search);

    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setIconifiedByDefault(true);

    SearchView.SearchAutoComplete searchAutoComplete = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
    searchView.setBackgroundColor(Color.WHITE);
    searchAutoComplete.setAdapter(new CustomAdapter(this,new ArrayList<>(Arrays.asList(languages))));

    searchAutoComplete.setOnItemClickListener((adapterView, view, i, l) -> {
        String shopName = ((TextView)view.findViewById(R.id.shop_name)).getText().toString();
        Toast.makeText(this,shopName,Toast.LENGTH_SHORT).show();
    });
    return true;
}

and this is the xml for the

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/app_bar_search"
    android:icon="@drawable/ic_search_black_24dp"
    android:title="Search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always|withText|collapseActionView"/>

and this is the result enter image description here


Solution

  • The default appearance of android.support.v7.widget.searchview is not what you desire. however, it's a common view in android and there are many good libraries.

    I suggest you use a library that can help you like this one https://github.com/arimorty/floatingsearchview

    enter image description here