I am using Search view on the toolbar. I ran into a problem with a related icon. It works like on a mobile phone, but does not work on Android tablets. On the tablet, it appears in the middle of the action bar instead of the right side.
As the picture below:
In a mobile phone (correct):
On the tablet (incorrect):
My XML code is:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="collapseActionView|ifRoom"
android:icon="@mipmap/ic_search_white_24dp"
android:title="Search" />
</menu>
My JAVA code:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_search_view_explore_ideas, menu);
SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setQueryHint("Search...");
((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)).setTextColor(Color.WHITE);
((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)).setHintTextColor(getResources().getColor(R.color.notify_user_color));
if (searchManager != null) {
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
}
AutoCompleteTextView searchTextView = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.cursor_for_search_view);
} catch (Exception e) {
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
mAdapter.getFilter().filter(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});
}
Let me know if I missed something.
source
share