Android菜单项更新数量问题



我正在制作一个应用程序,该应用程序通过线程生成属于特定条件的人员的负载,但该数字未在菜单项通知中更新。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu (menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
//En esta parte llamaremos nuestro item que creamos en menu
MenuItem item = menu.findItem(R.id.action_notification);
setBadgeCount((LayerDrawable) item.getIcon(), String.valueOf(Const.NOTIFICA_PERSON_ACTIVE));
/*Llamamos nuestro método setBadgeCount y enviamos los argumentos que seria el icono y el número de notificaciones */
threadAlertNotify = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
int migrationLapse = 15 * 1000;
List<enConfiguration> lst = new ArrayList<enConfiguration>();
lst = appdbConfig.getAllConfiguration();
if (lst.size() > 0) {
migrationLapse = lst.get(0).getMigrationLapse() * 1000;
}
Thread.sleep(migrationLapse);
MenuItem item = menu.findItem(R.id.action_notification);
setBadgeCount((LayerDrawable) item.getIcon(), String.valueOf(Const.NOTIFICA_PERSON_ACTIVE));
Log.v("Hilo3", "3AlertNotifiTrue - "+String.valueOf(Const.NOTIFICA_PERSON_ACTIVE) + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
threadAlertNotify.start();
return  true;
}
public void setBadgeCount(LayerDrawable icon, String count){
//Creamos una instancia de nuestra clase Circle
CircleNoty circle=new CircleNoty();
//Llamamos nuestro método setCount y enciamos el numero de notificaciones
circle.setCount(count);
/*Mutable no compartirá su estado con ningún otro sorteo.*/
icon.mutate();
/*como les mencione anteriormente creamos dos capas una para la notificación y otra para agregar el circulo rojo en esta línea llamamos la capa y agregamos el circulo*/
icon.setDrawableByLayerId(R.id.ic_badge, circle);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_notification:
customAlertDialogActivedPerson = new CustomAlertDialogActivedPerson(MainActivity.this,"N");
customAlertDialogActivedPerson.show(MainActivity.this.getSupportFragmentManager(),"customAlertDialogActivedPerson");
return true;
case R.id.btnSalir:
//Toast.makeText(this,"Salir", Toast.LENGTH_LONG).show();
CloseSession();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

在那个线程中,我应该改变数字,但什么都没有发生,直到我点击图标,似乎需要刷新图标,每次执行线程时都会有一个代码来刷新它。

输入图片描述

据我所知,你没有打电话invalidateOptionsMenu方法。当您更新菜单项并希望它们自动刷新时,应该调用该函数。此外,在运行时执行菜单操作的正确位置是onPrepareOptionsMenu方法。

From Android Documentation,

public boolean onPrepareOptionsMenu(菜单菜单)准备屏幕显示标准选项菜单。这就叫做菜单显示,每次显示。你可以用这个方法来有效地启用/禁用项或以其他方式动态修改内容。

另外,你正在使用一个新线程,所以无论你在后台做什么,在菜单创建过程中,将在菜单第一次创建后完成。

你最好的选择是,当你想要更新你的徽章号码和存储数字(需要在菜单中显示)的逻辑分开的代码,所以你可以从onPrepareOptionsMenu方法访问它。然后,每次你想刷新图标时,调用invalidateOptionsMenu()

最重要的是,请记住,当你在Android中更新视图时,你总是需要从主线程中完成。

我建议在这里查看android中创建菜单的文档

最新更新