The code on which I am working, is using a Toolbar and inflating a menu.
Here is the code
private Toolbar mToolbar;
mToolbar.inflateMenu(R.menu.chat_screen_menu);
setupMenu ();
private void setupMenu ()
{
mMenu = mToolbar.getMenu();
if (mMenu != null)
{
if (mChatPager != null && mChatPager.getCurrentItem() > 0)
{
mMenu.setGroupVisible(R.id.menu_group_chats, true);
mMenu.setGroupVisible(R.id.menu_group_contacts, false);
}
else
{
mMenu.setGroupVisible(R.id.menu_group_chats, false);
mMenu.setGroupVisible(R.id.menu_group_contacts, true);
mMenu.setGroupVisible(R.id.menu_group_otr_verified,false);
mMenu.setGroupVisible(R.id.menu_group_otr_unverified,false);
mMenu.setGroupVisible(R.id.menu_group_otr_off,false);
}
}
mToolbar.setOnMenuItemClickListener(new OnMenuItemClickListener ()
{
..........
}
}
But now, they require a Search button in the tool_bar.
I managed to put it, I followed a guide here
When I try to write something to search, the toast I had put to test the listener never shown.
which indicates listener is not working
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chat_screen_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_menu_search));
final Toast toast = new Toast(mApp);
if (mSearchView != null )
{
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener()
{
public boolean onQueryTextChange(String newText)
{
mSearchString = newText;
//doFilterAsync(mSearchString);
toast.makeText(getApplicationContext(), "Test1", Toast.LENGTH_LONG).show();
return true;
}
public boolean onQueryTextSubmit(String query)
{
mSearchString = query;
//doFilterAsync(mSearchString);
toast.makeText(getApplicationContext(), "Test2", Toast.LENGTH_LONG).show();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
}
return true;
}
You have to use Appcompat library for that. Which is used like below:
dashboard.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:title="Search"/>
</menu>
Activity file (in Java):
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.dashboard, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
Activity file (in Kotlin):
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView: SearchView? = searchItem?.actionView as SearchView
searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
return super.onCreateOptionsMenu(menu)
}
manifest file:
<meta-data
android:name="android.app.default_searchable"
android:value="com.apkgetter.SearchResultsActivity" />
<activity
android:name="com.apkgetter.SearchResultsActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
searchable xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint"
android:label="#string/app_name" />
And at last, your SearchResultsActivity class code. for showing result of your search.
If you would like to setup the search facility inside your Fragment, just add these few lines:
Step 1 - Add the search field to you toolbar:
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
Step 2 - Add the logic to your onCreateOptionsMenu()
import android.support.v7.widget.SearchView; // not the default !
#Override
public boolean onCreateOptionsMenu( Menu menu) {
getMenuInflater().inflate( R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// Toast like print
UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
if( ! searchView.isIconified()) {
searchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// UserFeedback.show( "SearchOnQueryTextChanged: " + s);
return false;
}
});
return true;
}
If you want to add it directly in the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:id="#+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_centerHorizontal="true" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Integrating SearchView with RecyclerView
1) Add SearchView Item in Menu
SearchView can be added as actionView in menu using
app:useActionClass = "android.support.v7.widget.SearchView"
.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="#+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
2) Implement SearchView.OnQueryTextListener in your Activity
SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
3) Set up SerchView Hint text, listener etc
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
4) Implement SearchView.OnQueryTextListener
This is how you can implement abstract methods of the listener.
#Override
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
5) Write a filter method in your RecyclerView Adapter.
You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App
Implementing the SearchView without the use of the menu.xml file and open through button
In your Activity we need to use the method of the onCreateOptionsMenumethod in which we will programmatically inflate the SearchView
private MenuItem searchMenu;
private String mSearchString="";
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
mSearchView.setMaxWidth(Integer.MAX_VALUE);
searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
assert searchManager != null;
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
mSearchString = newText;
return true;
}
public boolean onQueryTextSubmit(String query) {
mSearchString = query;
searchMenu.collapseActionView();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
return true;
}
And in your Activity class, you can open the SearchView on any button click on toolbar like below
YOUR_BUTTON.setOnClickListener(view -> {
searchMenu.expandActionView();
});
I search and implement so much code but that not worked for me .
Then I implement custom toolbar into my XML file and then inside toolbar tag I use searchview tag.
Hope it work for you.
Related
I am using Search view in the toolbar. I am facing issue with the close icon.
It is working as excepted on mobile but not working on Android tablets. On the tablet, it is showing in the middle of the action bar instead of right side.
As shown in below images:
On Mobile (Correct):
On Tablet (Incorrect):
My XML Code:
<?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); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} 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 am missing something.
you try like this in your onCreateOptionsMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search_view_explore_ideas, menu);
SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
In your onCreateOptionsMenu() try this for searchView after inflating menu,
searchView.setMaxWidth(Integer.MAX_VALUE);
In your onCreateOptionsMenu()
try following code for searchView after inflating menu,
SearchView searchView= (SearchView)menu.findItem(R.id.action_search).getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
Try this on onCreateOptionsMenu
searchView.setMaxWidth(Integer.MAX_VALUE);
In your OnCreateView
make following change
final SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
I am working on the following screen:
1 Screenshot
Here on the toolbar ,i am having a search icon.To add this search icon ,i have used the following code:
menu_friend_list_activity.xml
<?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"
android:icon="#drawable/search"
android:orderInCategory="100"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
Code inside Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_friend_list_activity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Search button clicked", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
On clicking search icon i want to display the SearchView in toolbar(if i am not wrong here).In short i want to implement the following screen:
Please tell me how can i implement this.Search will be different for different fragments.
try this
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_actions, menu);
MenuItem searchViewItem = menu.findItem(R.id.action_search);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) searchViewItem.getActionView();
searchView.setQueryHint("Search for Product,Brands...");
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);// Do not iconify the widget; expand it by defaul
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
// This is your adapter that will be filtered
Toast.makeText(getApplicationContext(),"textChanged :"+newText,Toast.LENGTH_LONG).show();
return true;
}
public boolean onQueryTextSubmit(String query) {
// **Here you can get the value "query" which is entered in the search box.**
Toast.makeText(getApplicationContext(),"searchvalue :"+query,Toast.LENGTH_LONG).show();
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return true;
}
Your not inflating the menu correctly, Here is how your supposed to inflate it to get the screen you want
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.yourmenyxml, menu);
item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
I had similar issue. and I solved as following:
MenuItem searchItem = menu.findItem(R.id.ot_action_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchItem.expandActionView();
searchView.setIconified(false);
searchView.setQuery(searchQuery, false);
NB: the expandActionView() should be invoked on searchItem menu item not on the searchView. that was my mistake.
I have tried the other possible answer provided in stackoverflow but none of them is working so I am posting it here again.
The problem is I want to open the softkeyboard automatically when the activity opens, but none of the ways I have tried is working.
My Activity code where I am setting SearchView:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) SelectCityActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(SelectCityActivity.this.getComponentName()));
searchView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
searchView.setQueryHint(searchHint);
searchView.setIconifiedByDefault(false);
final SearchView finalSearchView = searchView;
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
showInputMethod(view);
finalSearchView.onActionViewExpanded();
}
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String s) {
valueAdapter.getFilter().filter(Methods.capitalize(s));
return true;
}
});
}
return true;
}
And menu xml file:
<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"
android:icon="#android:drawable/ic_menu_search"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
Just call this line in your code
searchView.requestFocus();
That's it.
Put below code on onCreate of Activity:
((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Hope this will help you.
try this to force open soft keyboard:
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
I have an activity that shows search in title bar perfectly, but right now i want to get the text entered in search in action bar to a string. Please help !
Her is my menu/xml
<?xml version="1.0" encoding="utf-8"?>
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView"
/>
</menu>
Her is the code in onCreate
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Have you used searchView? You can use following code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
.getActionView();
if (null != searchView) {
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
// This is your adapter that will be filtered
return true;
}
public boolean onQueryTextSubmit(String query) {
// **Here you can get the value "query" which is entered in the search box.**
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
If you are using a Toolbar you can do this:
MenuItem menuItem = getToolbar().getMenu().findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Log.i("well", " this worked");
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.i("well", " this worked");
return false;
}
});
In the following screenshot, the SearchView widget in the ActionBar does not take up the entire space available.
I need it to take up all the horizontal space present in the ActionBar (so it spans the entire screen horizontally).
What I tried:
Programatically, tried this in the onCreateOptionsMenu:
View searchViewView = (View) searchView;
searchViewView.getLayoutParams().width=LayoutParams.MATCH_PARENT;`
This gives:
java.lang.NullPointerException: Attempt to write to
field 'int android.view.ViewGroup$LayoutParams.width' on a null
object reference ...
TestActionBarTwo.MainActivity.onCreateOptionsMenu(MainActivity.java:57)
and in the menu resource:
The android:layout_width="match_parent" does not seem to affect
anything.
I also tried android:layout_weight="1" (assuming that the
ActionBar has a LinearLayout), but that doesn't work either.
So is there a way that the SearchView (not iconified) takes up the entire horizontal space of the ActionBar?
EDIT 1
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "onCreateOptionsMenu OF MainActivity CALLED."); //check
getMenuInflater().inflate(R.menu.activity_main_action_bar_menu, menu);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// SearchAction
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
//Adding event listeners
searchView.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
Log.i(TAG, "onFocusChange OF ONFocusChangeListener IN MainActivity CALLED."); //check
}
});
return super.onCreateOptionsMenu(menu);
}
And the menu resource is:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:testactionbartwo="http://schemas.android.com/apk/res-auto" >
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/mainActivity_searchActionTitle"
testactionbartwo:showAsAction="always"
testactionbartwo:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Edit 2: Even when I DO NOT set setIconifiedByDefault(false), even though it does not seem relevant:`
Code change:
// SearchAction
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//searchView.setIconifiedByDefault(false);************************
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Result, when I clicked the iconified search icon to expand it:
Edit 3: Copied code from the answer by #MaheeraJazi , still doesn't seem to work. I am now posting the entire SSCCE:
MainActivity.java:-
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate OF MainActivity CALLED."); // check
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
Log.i(TAG, "onNewIntent OF MainActivity CALLED."); // check
handleIntent(intent);
setIntent(intent);
}
private void handleIntent(Intent intent) {
Log.i(TAG, "handleIntent OF MainActivity CALLED."); // check
if (intent.getAction().equals(Intent.ACTION_SEARCH)) {
showResults(intent.getStringExtra(SearchManager.QUERY));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "onCreateOptionsMenu OF MainActivity CALLED."); // check
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_action_bar_menu, menu);
// SearchAction
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchMenuItem = menu.findItem(R.id.mainActivity_actionSearch);
SearchView searchViewActionView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
searchViewActionView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewActionView.setIconifiedByDefault(true);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
Log.i(TAG, "onQueryTextChange OF OnQueryTextListener IN MainActivity CALLED.");//check
// this is your adapter that will be filtered
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Log.i(TAG, "onQueryTextChange OF OnQueryTextListener IN MainActivity CALLED.");//check
return true;
}
};
searchViewActionView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
Log.i(TAG, "onOptionsItemSelected OF MainActivity CALLED."); // check
switch (menuItem.getItemId()) {
case R.id.mainActivity_actionSearch:
onSearchRequested();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
private void showResults(String searchQuery) {
Log.i(TAG, "showResults OF MainActivity CALLED."); // check
}
}
activity_main_action_bar_menu.xml:-
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:testactionbartwo="http://schemas.android.com/apk/res-auto" >
<item android:id="#+id/mainActivity_actionSearch"
android:icon="#drawable/ic_action_search"
android:title="#string/mainActivity_searchActionTitle"
testactionbartwo:showAsAction="always"
testactionbartwo:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
activity_main.xml:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
Manifest File:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="khanZarah.tests.TestActionBarTwo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light"
android:launchMode="singleTop"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data android:name="android.support.UI_OPTIONS"
android:value="splitActionBarWhenNarrow" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<meta-data android:name="android.app.default_searchable"
android:value=".MainActivity"/>
</application>
The default width of the search view in toolbar is defined by non-public attribute abc_search_view_preferred_width. It set to 320dp for all screen sizes.
A workaround is to set maxWidth of SearchView:
searchView.setMaxWidth(Integer.MAX_VALUE);
Acutely you don't need to specify android:layout_weight or any other properties. In my code I do that and everything goes well !
On main Menu you need to add this:
<!-- Search, should appear as action button -->
<item
android:id="#+id/action_search"
android:icon="#drawable/searchmenu"
android:title="#string/search"
yourapp:showAsAction="always"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
/>
<item
On your Activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_menu, menu);
// SearchAction
SManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.action_search);
searchViewAction = (SearchView) MenuItemCompat
.getActionView(searchMenuItem);
searchViewAction.setSearchableInfo(SManager
.getSearchableInfo(getComponentName()));
searchViewAction.setIconifiedByDefault(true);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
// this is your adapter that will be filtered
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// this is your adapter that will be filtered
return true;
}
};
searchViewAction.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
The photo look like:
when getSupportActionBar().setDisplayShowHomeEnabled(false) the searchview look like:
I hope this help!