Reputation: 1299
I am working on the following screen:
On the Toolbar you can see a single tick.I want to display text "Create" along with this also.I am using the following code:
menu_new_group
<?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/createGroup"
android:icon="@drawable/single_tick"
android:orderInCategory="100"
android:showAsAction="always|withText"
android:title="Create"
app:showAsAction="always|withText" />
</menu>
Code using option menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_new_group, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.createGroup:
createNewGroup();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Please help me to add both text and icon as actions in the toolbar.
Upvotes: 0
Views: 1535
Reputation: 4781
FYI, It is not possible to show Icon as well as Text of an Action Menu simultaneously in a small spaced Action bar. So we need to make use of
actionLayout
feature to display icon + text.
Check the below sample code for implementation.
Menu XML
<menu
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto">
<item
android:id = "@+id/menu_profile"
android:icon = "@android:drawable/ic_menu_save"
android:title = "Save"
app:actionLayout = "@layout/action_menu"
app:showAsAction = "always"/>
</menu>
Action Layout - like a normal Layout file with only Textview. action_menu.xml
<TextView
xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:background = "@drawable/tab_selector"
android:drawableRight = "@android:drawable/ic_menu_save"
android:gravity = "center"
android:text = "Save"
android:textColor = "@android:color/white"/>
Background Selector - for highlighting when clicked. tab_selector.xml
<selector xmlns:android = "http://schemas.android.com/apk/res/android">
<item
android:drawable = "#eeeeee"
android:state_pressed = "true"/>
<item
android:drawable = "@android:color/transparent"/>
</selector>
In Code, set click listener as below in onCreateOptionsMenu.
MenuItem item = menu.findItem(R.id.menu_profile);
item.getActionView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Activity.this, "Save Clicked..", Toast.LENGTH_SHORT).show();
}
});
Best Wishes..
Upvotes: 2