Android Action Bar SearchView as Autocomplete?
I have use custom AutoCompleteTextView and add it in ActionBar.
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.
How to implement search view autocomplete in actionbar using http request?
You can't do this with setSearchableInfo()
and a search configuration.
The problem is that SearchView
needs a CursorAdapter
and you are retrieving data from the server, not the database.
However, I have done something like this before with these steps:
Set up your
SearchView
to use aCursorAdapter
;searchView.setSuggestionsAdapter(new SimpleCursorAdapter(
context, android.R.layout.simple_list_item_1, null,
new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1 },
new int[] { android.R.id.text1 }));Create an
AsyncTask
to read the JSON data from your server and create aMatrixCursor
from the data:public class FetchSearchTermSuggestionsTask extends AsyncTask<String, Void, Cursor> {
private static final String[] sAutocompleteColNames = new String[] {
BaseColumns._ID, // necessary for adapter
SearchManager.SUGGEST_COLUMN_TEXT_1 // the full search term
};
@Override
protected Cursor doInBackground(String... params) {
MatrixCursor cursor = new MatrixCursor(sAutocompleteColNames);
// get your search terms from the server here, ex:
JSONArray terms = remoteService.getTerms(params[0]);
// parse your search terms into the MatrixCursor
for (int index = 0; index < terms.length(); index++) {
String term = terms.getString(index);
Object[] row = new Object[] { index, term };
cursor.addRow(row);
}
return cursor;
}
@Override
protected void onPostExecute(Cursor result) {
searchView.getSuggestionsAdapter().changeCursor(result);
}
}Set an
OnQueryTextListener
to kick off your remote server task or start your search activity:searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String query) {
if (query.length() >= SEARCH_QUERY_THRESHOLD) {
new FetchSearchTermSuggestionsTask().execute(query);
} else {
searchView.getSuggestionsAdapter().changeCursor(null);
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// if user presses enter, do default search, ex:
if (query.length() >= SEARCH_QUERY_THRESHOLD) {
Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
intent.setAction(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY, query);
startActivity(intent);
searchView.getSuggestionsAdapter().changeCursor(null);
return true;
}
}
});Set an
OnSuggestionListener
on theSearchView
to execute your search:searchView.setOnSuggestionListener(new OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
Cursor cursor = (Cursor) searchView.getSuggestionsAdapter().getItem(position);
String term = cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
cursor.close();
Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
intent.setAction(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY, term);
startActivity(intent);
return true;
}
@Override
public boolean onSuggestionClick(int position) {
return onSuggestionSelect(position);
}
});
Android - searchview with auto complete feature inside action bar
For this I have Create one Layout with AutoCompleteTextView
and add it in ActionBar
its call Custom layout in ActionBar.
After that I have Create Adapter with android.R.layout.simple_dropdown_item_1line
. set it in AutoCompleteTextView
.
check Below Code:
package com.example.testapp;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
@TargetApi(11)
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);
}
}
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>
For More Details check this articals: one, two and three
Best Luck!
Turn AutoCompleteTextView into a SearchView in ActionBar instead
To get Places Autocomplete API results in a SearchView, you'll first need a ContentProvider for the API.
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
public class PlacesSuggestionProvider extends ContentProvider {
private static final String LOG_TAG = "ExampleApp";
public static final String AUTHORITY = "com.example.google.places.search_suggestion_provider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/search");
// UriMatcher constant for search suggestions
private static final int SEARCH_SUGGEST = 1;
private static final UriMatcher uriMatcher;
private static final String[] SEARCH_SUGGEST_COLUMNS = {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
};
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
}
@Override
public int delete(Uri uri, String arg1, String[] arg2) {
throw new UnsupportedOperationException();
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case SEARCH_SUGGEST:
return SearchManager.SUGGEST_MIME_TYPE;
default:
throw new IllegalArgumentException("Unknown URL " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues arg1) {
throw new UnsupportedOperationException();
}
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Log.d(LOG_TAG, "query = " + uri);
// Use the UriMatcher to see what kind of query we have
switch (uriMatcher.match(uri)) {
case SEARCH_SUGGEST:
Log.d(LOG_TAG, "Search suggestions requested.");
MatrixCursor cursor = new MatrixCursor(SEARCH_SUGGEST_COLUMNS, 1);
cursor.addRow(new String[] {
"1", "Search Result", "Search Result Description", "content_id"
});
return cursor;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
@Override
public int update(Uri uri, ContentValues arg1, String arg2, String[] arg3) {
throw new UnsupportedOperationException();
}
}
Then add your Places Autocomplete API client code into the query method on the content provider. You extract the user input as follows:
String query = uri.getLastPathSegment().toLowerCase();
Add the PlacesSuggestionProvider to your AndroidManifest, and make sure your activity has a searchable configuration.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity android:name=".PlacesSearchViewActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
<provider
android:name="com.example.google.places.PlacesSuggestionProvider"
android:authorities="com.example.google.places.search_suggestion_provider"
android:syncable="false" />
</application>
</manifest>
And make sure your searchable configuration (res/xml/searchable.xml) has a search suggest authority.
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint"
android:searchSuggestAuthority="com.example.google.places.search_suggestion_provider">
</searchable>
The authority should be the same in AndroidManifest.xml, searchable.xml, and your content provider.
Create a options menu for your ActionBar that includes a SearchView (/res/menu/options_menu.xml).
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_search"
android:title="@string/menu_search"
android:icon="@drawable/ic_menu_search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
Configure your Activity with a SearchView that's associated with your searchable configuration/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
// Tells your app's SearchView to use this activity's searchable configuration
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
return true;
}
A few key docs are:
Adding Custom Suggestions:
http://developer.android.com/guide/topics/search/adding-custom-suggestions.html
Creating a Content Provider:
http://developer.android.com/guide/topics/providers/content-provider-creating.html
Using a Search Widget:
http://developer.android.com/guide/topics/search/search-dialog.html#UsingSearchWidget
Search autocomplete android
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
SearchView AutoComplete is appearing with Black border and covering the searchtext?
I Found my Question answer It is problem because I was trying to override the theme Appcompat.light through
searchAutoComplete.setDropDownBackgroundResource(android.R.color.white);
So as soon as I removed this statement the border was removed.
Related Topics
Getactionbar() Returns Null (Appcompat-V7 21)
Apache Http Connection with Android 6.0 (Marshmallow)
Get File Path of Image on Android
Mediarecorder Start Failed: -38
Android Devices with Different Height Takes Same Layout Folder
Android Volley Self Signed Https Trust Anchor for Certification Path Not Found
What's the Maximum Size for an Android Shared Preference Value
Google Maps API V2 'Failed to Load Map. Could Not Contact Google Servers'
Jpeg Images Have Different Pixel Values Across Multiple Devices
Mapview Rendering with Tiles Missing with an "X" in the Center
How to Keep a Countdowntimer Running Even If the App Is Closed
Android Room - Select Query with Like
Remove Vertical Padding from Horizontal Progressbar
Android Show Notification with a Popup on Top of Any Application
Session 'App' Error While Installing APK
Getting "Debuggable" Value of Androidmanifest from Code
How to Order My SQLite Database in Descending Order, for an Android App