0

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);
}
124697
  • 22,097
  • 68
  • 188
  • 315

2 Answers2

0

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);
        }
    });
}
ugo
  • 2,705
  • 2
  • 30
  • 34
-1

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);
        }
    }
Community
  • 1
  • 1
carlosmaciel
  • 801
  • 1
  • 6
  • 17
  • This code has ERRORS, it only removes last 3 character and puts three dots at the end. This is NOT what you would expect from ellipsizing. – NecipAllef May 20 '18 at 16:19