How to display both icon and title of action inside ActionBar?
Solution 1:
'always|withText' will work if there is sufficient room, otherwise it will only place icon. You can test it on your phone with rotation.
<item android:id="@id/menu_item"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />
Solution 2:
You can create actions with text in 2 ways:
1- From XML:
<item android:id="@id/resource_name"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="withText" />
When inflating the menu, you should call getSupportMenuInflater()
since you are using ActionBarSherlock
.
2- Programmatically:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Make sure you import com.actionbarsherlock.view.Menu
and com.actionbarsherlock.view.MenuItem
.
Solution 3:
What worked for me was using 'always|withText'. If you have many menus, consider using 'ifRoom' instead of 'always'.
<item android:id="@id/resource_name"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />
Solution 4:
The solution I find is to use custom action Layout: Here is XML for menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:Eventapp="http://schemas.android.com/apk/res-auto">
<!-- This is a comment. -->
<item
android:id="@+id/action_create"
android:actionLayout="@layout/action_view_details_layout"
android:orderInCategory="50"
android:showAsAction = "always"/>
</menu>
The Layout is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:gravity="center"
android:text="@string/create"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:gravity="center"
android:src="@drawable/ic_action_v"/>
</LinearLayout>
this will show the icon and the text together.
To get the clickitem the the fragment or activity:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
//super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_details_fragment, menu);
View view = menu.findItem(R.id.action_create).getActionView();
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
Solution 5:
If any1 in 2017 is wondering how to do this programmatically, there is a way that i don't see in the answers
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);