Reputation: 18712
In my Android application I have a TextView declared in the following way:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
[...]
<item
android:id="@+id/intro_button"
android:showAsAction="ifRoom"
android:title="@string/intro_button"/>
<item
android:id="@+id/help_button"
android:showAsAction="always|withText"
android:title="@string/help_button"/>
[...]
<item
android:id="@+id/user_id_label"
android:actionViewClass="android.widget.TextView"
android:showAsAction="ifRoom"
android:title="@string/session_info_label"/>
</menu>
At the start of an application, activity 1 is launched (it doesn't use the action bar). When it is completed, it starts activity 2, in which the action bar is displayed.
At the start of the activity 2 I need to set the text of the view @+id/user_id_label
to a certain value.
I tried to do it in Activity2.onCreate
and in Activity2.onCreateOptionsMenu
, but in both these methods findViewById(R.id.user_id_label)
returns null
.
How (using which method) can I retrieve the reference to @+id/user_id_label
text view?
Update 1 (28.04.2013 20:25):
I tried this:
@Override
public boolean onCreateOptionsMenu(final Menu aMenu) {
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actions, aMenu);
this.menu = aMenu;
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu aMenu) {
final MenuItem menuItem = this.menu.findItem(R.id.user_id_label);
menuItem.setTitle(getString(R.string.user_id_text,
getIntent().getIntExtra(ConnectToServerActivity.USER_ID, -1)));
return super.onPrepareOptionsMenu(aMenu);
}
But the label is still not shown.
Update 2 (28.04.2013 21:05):
This one works (in method onPrepareOptionsMenu
):
final TextView textView = (TextView) menuItem.getActionView();
textView.setText(...);
Upvotes: 3
Views: 8484
Reputation: 72553
Save a reference to your OptionsMenu
in a field variable:
Menu mMenu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
[...]
this.mMenu = menu;
return true;
}
Then you can do something like this:
MenuItem myMenuItem = mMenu.findItem(R.id.user_id_label);
myMenuItem.setTitle("New title!");
Upvotes: 2