在动作条动态的TextView [英] Dynamic TextView on ActionBar

查看:105
本文介绍了在动作条动态的TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现的动作条一个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的冠军,但增加一个TextView FE在标题之下,或在右侧。

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);
}

但它不能正常工作。在第一次应显示断开状态,并没有表现出什么。然后,当状态变化和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.

推荐答案

您可以添加TextView的手动

You can Add TextView manually in

@Override
public boolean onCreateOptionsMenu(Menu menu) {

通过以下code。

By following code.

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);

如果您要访问文本视图,则使电视作为类变量。

and if you want to access text view then make tv as class variable.

这篇关于在动作条动态的TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆