i want to change some titles out of my Activites programmatically. I have some items like
"Show/Hide something1" "Show/Hide something2"
And now i want to change the text to:
"Show something1" and do some action, and change the text of this Menu item to:
"Hide something1" .....
i test this Solution, and get a null Pointer
My Layout:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:universal="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_1"
universal:showAsAction="never"
android:title="Show/Hide Something1" />
<item
android:id="@+id/menu_2"
universal:showAsAction="never"
android:title="Show/Hide Something2" />
</menu>
And my 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.rallye_menu, menu);
MenuItem item=menu.getItem(R.id.menu_1); // here itemIndex is int
item.setTitle("YourTitle");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_1:
// do some action
return true;
case R.id.menu_2:
// doe other action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Got this Error:
Process: com.packagename.foo, PID: 12441 java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setTitle(java.lang.CharSequence)' on a null object reference at com.sherdle.universal.rallye.MainActivity.onCreateOptionsMenu(MainActivity.java:646)
in this line: MenuItem item=menu.getItem(R.id.menu_1)
Need help :)
EDIT: found another Solution: Android - How to dynamically change menu item text outside of onOptionsItemsSelected or onCreateOptionsMenu but does not work