gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:14 25 4
gpt4 key购买 nike

我有一个带有静态变量的服务,该变量保存从附加到 Activity 以来耗时量

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 的值,任何帮助表示赞赏。

最佳答案

创建 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();
}
}

关于java - 如何从服务动态更新工具栏中菜单项的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com