Search code examples
androidautocompleteautocompletetextviewsearchview

Android Action Bar SearchView as Autocomplete?


I am using a SearchView in the Action Bar. I want to use autocomplete feature on the search view to get results from the database.

Is this possible? Or do I need to use a custom text box and then add autocomplete to that?


Solution

  • I have use custom AutoCompleteTextView and add it in ActionBar.

    enter image description here

    public class MainActivity extends Activity {
    
        private static final String[] COUNTRIES = new String[] { "Belgium",
                "France", "France_", "Italy", "Germany", "Spain" };
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            ActionBar actionBar = getActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
            // actionBar.setDisplayShowTitleEnabled(false);
            // actionBar.setIcon(R.drawable.ic_action_search);
    
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar, null);
    
            actionBar.setCustomView(v);
    
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_dropdown_item_1line, COUNTRIES);
            AutoCompleteTextView textView = (AutoCompleteTextView) v
                    .findViewById(R.id.editText1);
            textView.setAdapter(adapter);
    
        }
    
    }
    

    and Your Layout:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Action Bar:"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#FFFFFF" />
    
        <AutoCompleteTextView
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:imeOptions="actionSearch"
            android:inputType="textAutoComplete|textAutoCorrect"
            android:textColor="#FFFFFF" >
    
            <requestFocus />
        </AutoCompleteTextView>
    
    </LinearLayout>
    

    Edited:

    Please check this and this link it may help you. code is here.