ActionBar 上的动态 TextView [英] Dynamic TextView on ActionBar
问题描述
我需要在 ActionBar 中实现一个 TextView.此 TextView 显示蓝牙连接的状态,因此它将根据此状态进行更新.
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.
我不是在谈论更改 ActionBar 的标题,而是在添加文本视图 f.e.在标题下或右侧.
I'm not talking about changing ActionBar's title, but adding a textview f.e. under the title or at the right side.
目前,我所做的是在 menu.xml 中创建一个项目:
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" />
然后在mainActivity中添加:
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);
}
但是它不能正常工作.第一次应该显示 Disconnected
状态并且不显示任何内容.然后当状态改变并且 textview 必须更新时,它会抛出一个 NPE.
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.
推荐答案
可以在
@Override
public boolean onCreateOptionsMenu(Menu menu) {
通过以下代码.
TextView tv = new TextView(this);
tv.setText(getString(R.string.matchmacking)+" ");
tv.setTextColor(getResources().getColor(R.color.WHITE));
tv.setOnClickListener(this);
tv.setPadding(5, 0, 5, 0);
tv.setTypeface(null, Typeface.BOLD);
tv.setTextSize(14);
menu.add(0, FILTER_ID, 1, R.string.matchmacking).setActionView(tv).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
如果你想访问文本视图,那么将 tv 作为类变量.
and if you want to access text view then make tv as class variable.
这篇关于ActionBar 上的动态 TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!