4

I'm trying to create a TextView in the menu, the text is to be set dynamically. Right now my menu has this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_search"
        android:actionViewClass="android.widget.SearchView"
        android:icon="@android:drawable/ic_menu_search"
        android:showAsAction="ifRoom"
        android:title="Search"/>
    <item
        android:id="@+id/action_sync"
        android:icon="@drawable/ic_menu_refresh"
        android:showAsAction="ifRoom"
        android:title="Sync"/>

</menu>

How can I create an item which has only text?

Jainendra
  • 24,713
  • 30
  • 122
  • 169

2 Answers2

3

If you want to just show text, simply don't add an icon in menu.xml. If you want to change the text in code, you can do so in the onPrepareOptionsMenu() on your activity callback as such:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem myItem = menu.findItem(R.id.the_item);
    myItem.setTitle("bla");
    return true;
}
Tas Morf
  • 3,065
  • 1
  • 12
  • 8
1

I think if you want customization like, color, text size or font, you should have text view:

    String title = "MyTitle";

    TextView tvMiTitle = new TextView(getActivity());
    tvMiTitle.setText(title);
    tvMiTitle.setTextColor(Color.WHITE);
    // ==
    // MenuItem myMenuItem;
    myMenuItem.setActionView(tvMiTitle);
Abhinav Saxena
  • 1,990
  • 2
  • 24
  • 55
  • getActivity() you get this method when you are in a Fragment extended class. You can replace that with ((Activity)context) or "this" that points to Activity. – Abhinav Saxena Nov 04 '14 at 11:42
  • textview is aligned to right instead of left in navigation drawer – dgngulcan Jan 02 '17 at 14:09
  • Try Gravity: https://developer.android.com/reference/android/view/Gravity.html. , http://stackoverflow.com/questions/3775705/android-set-the-gravity-for-a-textview-programmatically – Abhinav Saxena Jan 09 '17 at 05:24