0

Is it possible to set the title of an Android Itemin the Java code. I know its possible in the xml file but I want to do it dynamically from within my Java Code. So this was my existing XML file:

 <item
     android:id="@+id/txn">
     android:title="@string/txn">
    <menu>
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/txn_item"
             />
        </group>
    </menu>
</item>

So i want to remove the android:title field and do it direct in Java. So far im trying to do it as follows, but get a NPE:

MenuItem  txn_type_item = (MenuItem) findViewById(R.id.txn);
txn_type_item.setTitle("TESTING!");

Is MenuItem not the right object type here? Or is there something else I am doing wrong?

maloney
  • 1,633
  • 3
  • 26
  • 49

2 Answers2

3

try this code..

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    MenuItem item=menu.getItem(itemIndex); // here itemIndex is int
    item.setTitle("YourTitle");
    return true;
}
Ketan Ahir
  • 6,678
  • 1
  • 23
  • 45
0

Do your changes inside onCreateOptionsMenu(Menu) and just call the InvalidateOptionsMenu(); whehenever you want to change the title.

Alex Chengalan
  • 8,211
  • 4
  • 42
  • 56