如何从服务动态更新工具栏中菜单项的标题

时间:2018-02-24 22:09:17

标签: java android

我有一个带有静态变量的服务,该变量保存从附加到活动后经过的时间

public class TimerService extends Service {
private static final String TAG = "TimerService";
Handler handler;
int Seconds, Minutes, MilliSeconds;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L;
static String timerTime = "";

private final IBinder iBinder = new MyBinder();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return iBinder;
}

public void updateTimerTime() {
    handler = new Handler();

    Runnable runnable = new Runnable() {

        public void run() {
            MillisecondTime = SystemClock.uptimeMillis() - StartTime;
            UpdateTime = TimeBuff + MillisecondTime;
            Seconds = (int) (UpdateTime / 1000);
            Minutes = Seconds / 60;
            Seconds = Seconds % 60;
            MilliSeconds = (int) (UpdateTime % 1000);
            timerTime = "" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds);
            handler.postDelayed(this, 0);
            Log.d(TAG, "run: time" + timerTime);

        }

    };

    StartTime = SystemClock.uptimeMillis();
    handler.postDelayed(runnable, 0);
}

public class MyBinder extends Binder {
    TimerService getService() {
        return TimerService.this;
    }
}
}

然后,我想通过做这样的事情来更新工具栏上菜单项的标题

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_main, menu);

    Intent intent = new Intent(this, TimerService.class);
    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

    timerService.updateTimerTime();
    final MenuItem timer = menu.findItem(R.id.timer);
    timer.setTitle(TimerService.timerTime);

    return super.onCreateOptionsMenu(menu);
}

显然它不会工作,因为onCreateOptionsMenu只被调用一次,它只会将文本设置为当菜单膨胀时任何TimerService.timerTime的值,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

创建一个Menu的全局对象,然后从您想要更改标题的位置访问该对象,最后调用invalidateOptionsMenu()。它将更新菜单更改。 类似的东西:

private Menu mMenu;

onCreate(....){
....
}

onCreateOptionsMenu(Menu menu){
this.mMenu = menu;
....
}

private void updateTitle(String title){
    if(mMenu!=null){
        final MenuItem timer = mMenu.findItem(R.id.timer);
        timer.setTitle(TimerService.timerTime);
        invalidateOptionsMenu();
    }
}