I need to implement a TextView in the ActionBar. This TextView shows the status of the bluetooth connection so it will update depending of this status.
I'm not talking about changing ActionBar's title, but adding a textview f.e. under the title or at the right side.
At the moment, what I have done is create an item in the menu.xml:
<item
android:id="@+id/statusTextview"
android:actionViewClass="android.widget.TextView"
android:showAsAction="ifRoom"
android:title="Disconected" />
Then Add it on the mainActivity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bluetooth, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final MenuItem menuItem = menu.findItem(R.id.statusTextview);
tvStatus = (TextView) menuItem.getActionView();
return super.onPrepareOptionsMenu(menu);
}
But It isn't working correctly. At first time should show Disconnected
status and doesn't show nothing. Then when the status changes and the textview must update, it throws a NPE.
Just in case anyone still needs this:
You can dynamically set the text property of menu item by calling the
setTitle("Your new string or String resource id")
method on the menu item. That way, you do not have to cast the ActionView into a TextView. For example:You can Add TextView manually in
By following code.
and if you want to access text view then make tv as class variable.