Reputation: 2745
I added a search to the Action bar by using the following code:
activity_main_actions.xml
<!-- Search -->
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"/>
<!-- Add -->
<item android:id="@+id/action_add_tip"
android:icon="@drawable/header_add"
android:title="@string/action_add_tip"
android:showAsAction="ifRoom" />
<!-- Count -->
<item android:id="@+id/action_count_tip"
android:icon="@drawable/header_count"
android:title="@string/action_count_tip"
android:showAsAction="ifRoom" />
in MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
searchable.xml
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Manifest.xml
<activity
android:name="com.emy.healthytips.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize"
android:launchMode="singleTop">
<meta-data
android:name="android.app.default_searchable"
android:value=".MainActivity" />
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
The search is working well with me, but the icon of the search in Action bar is still as it "Gray icon" like the following ScreenShot, although I added my own icon in
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
How can I add my own icon?
Upvotes: 3
Views: 6005
Reputation: 1997
This question ma be related with your problem. Please check it.
How to change the default icon on the SearchView, to be use in the action bar on Android?
Upvotes: 2