I need to ellipsize the end of each menu item. How can I target the textView in menuItem to setEllipsize
SubMenu sm = menuItem.getSubMenu();
for (int i = 0; i < sm.size(); i++) {
MenuItem mi = sm.getItem(i);
}
If defining the MenuItem
from XML, you can use android:actionLayout
to change the layout of the MenuItem. So you'll have:
<item android:id="@+id/button_id"
android:icon="@drawable/icon"
android:showAsAction="always"
android:actionLayout="@layout/action_button"
android:title="@string/text"/>
Then in layout/action_button, you could have:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ellipsize="end"
...
whatever other styles you need to set
...
/>
Keep in mind that if you do this, you may need to trigger onOptionsItemSelected yourself (if you're using ActionBarSherlock, for example). To accomplish that, do this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// inflate your menu
...
// Get the MenuItem of interest
final MenuItem item = menu.findItem(R.id.button_id);
item.getActionView().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
onOptionsItemSelected(item);
}
});
}
Please read the following link, it contains valuable information about when to ellipsis MenuItem titles:
When to use ellipsis after menu items
Unfortunately, I did not found an option to ellpsize MenuItem titles just like TextView method setEllipsize(), but if it is really something you must to do, you could solve it easily:
SubMenu sm = menuItem.getSubMenu();
String title = "";
for (int i = 0; i < sm.size(); i++) {
MenuItem mi = sm.getItem(i);
title = mi.getTitle().toString();
if (title.length() > 10) {
String truncated = title.subSequence(0, title.length() - 3).toString().concat("...");
mi.setTitle(truncated);
}
}