Android Action Bar SearchView as Autocomplete?

前端 未结 7 1296
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 04:00

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

相关标签:
7条回答
  • 2020-11-28 04:29

    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.

    0 讨论(0)
  • 2020-11-28 04:30

    Yes it is possible. Build a table (such as in an SQLiteDatabase) for your suggestions and format the table with required columns.

    See this link

    0 讨论(0)
  • 2020-11-28 04:33

    Here's an alternative method using CursorAdapter:

    ExampleActivity.java

    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 cursor = db.rawQuery("SELECT * FROM items", null); // Example database query
    
            SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    
            final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
    
            search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
    
            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(cursor.getString(cursor.getColumnIndex("text"))); // Example column index
    
        }
    
        @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;
    
        }
    
    }
    

    Please note: when you import CursorAdapter don't import the Android support version, import the standard android.widget.CursorAdapter instead.

    The adapter will also require 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>
    

    You can now customize list items by adding additional text or image views to the layout and populating them with data in the adapter. Now you 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 searchable 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 relevant 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 string used in the examples should be defined in values/strings.xml, also don't forget to update the reference to com.example for your project.

    Here's the original tutorial for reference:

    http://tpbapp.com/android-development/android-action-bar-searchview-tutorial

    0 讨论(0)
  • 2020-11-28 04:33

    I was also facing this issue for the auto complete search view and fix it without using any extra layout and auto complete text view, there is a class called SearchAutoComplete. I used this to achieve the auto complete feature, just put a simple list adapter which contain a ArrayList of items to suggest with search view. Set the adapter to your SearchAutoComplete and auto complete feature will work below is my code. Remember you don't have to add any custom layout. Just replace your onCreateOptionsMenu(...) method with mine code:

        @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);
    
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(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

      searchAutoComplete.setOnItemClickListener(new OnItemClickListener() {
    
        @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();
    
        }
        });
    
    0 讨论(0)
  • 2020-11-28 04:35

    You can do this with a CursorAdapter via something like:

    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    
    searchView.setSuggestionsAdapter(adapter);
    
    0 讨论(0)
  • 2020-11-28 04:44
        SearchAutoComplete searchAutoComplete = mSearchView.findViewById(androidx.appcompat.R.id.search_src_text);
    

    for androidx version

    0 讨论(0)
提交回复
热议问题