Alterair MenuItem cor do text por programação

Então eu tenho um item de menu, que é definido como:

<item android:id="@+id/action_live" android:title="@string/action_live" android:orderInCategory="1" app:showAsAction="ifRoom|withText" /> 

Ele mostra como text, como você pode view abaixo:

  • Como faço paira usair o FragmentPagerAdapter paira ter guias com conteúdo diferente?
  • Não é possível alterair o ícone da gaveta paira o NavigationDrawer
  • Usando a Declairação do Switch paira Controlair os Cliques do Botão
  • "Conviewsão paira o format Dalvik falhou com o erro 1" no JAR externo
  • como ocultair imagens da galeria do Android
  • No iOS, temos algo como Gradle Build Flavors no Android
  • Captura de tela 1

    E eu quero mudair programaticamente a cor do text "LIVE". Procurei por um tempo e findi um método:

    Com globalmente definido:

     private Menu mOptionsMenu; 

    e:

     @Oviewride public boolean onCreateOptionsMenu(Menu menu) { mOptionsMenu = menu; getMenuInflater().inflate(R.menu.menu_main, menu); return true; } retornair viewdadeiro; @Oviewride public boolean onCreateOptionsMenu(Menu menu) { mOptionsMenu = menu; getMenuInflater().inflate(R.menu.menu_main, menu); return true; } 

    Eu faço:

     MenuItem liveitem = mOptionsMenu.findItem(R.id.action_live); SpannableString s = new SpannableString(liveitem.getTitle().toString()); s.setSpan(new ForegroundColorSpan(Color.RED), 0, s.length(), 0); liveitem.setTitle(s); 

    Mas nada acontece!

    Se eu fizer o mesmo por um item do menu de transbordamento, ele funciona:

    Captura de tela 2

    Existe alguma limitação paira o aplicativo: os itens showAsAction = "ifRoom | withText"? Existe alguma solução alternativa?

    Desde já, obrigado.

  • Conecte-se a Raspberry Pi 3 usando adb
  • Usando o Emacs TRAMP com um server ssh que não fornece / bin / sh?
  • Dispositivo não está funcionando no aplicativo PhoneGap, como?
  • Ionic no Windows: Android SDK instalado. Ainda ganha "Erro: instale o Android paira alvo:" android-22 "
  • Mostrair image no TextView
  • USB_DEVICE_ATTACHED apenas stairtsActivity of Galaxy S3 ICS
  • 4 Solutions collect form web for “Alterair MenuItem cor do text por programação”

    Chegou tairde à festa com este, mas passei um tempo trabalhando nisso e findi uma solução, que pode ser útil paira qualquer outra pessoa tentando fazer o mesmo. Algum crédito vai paira Hairish Sridhairan por me orientair na direção certa.

    Você pode usair findViewById(R.id.MY_MENU_ITEM_ID) paira localizair o item do menu (desde que o menu tenha sido criado e prepairado) e lançá-lo paira uma instância TextView conforme sugerido por Hairish, que pode ser denominado conforme necessário.

     public class MyAwesomeActivity extends Activity { @Oviewride protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); // Force invalidatation of the menu to cause onPrepaireOptionMenu to be called invalidateOptionsMenu(); } private void styleMenuButton() { // Find the menu item you want to style View view = findViewById(R.id.YOUR_MENU_ITEM_ID_HERE); // Cast to a TextView instance if the menu item was found if (view != null && view instanceof TextView) { ((TextView) view).setTextColor( Color.BLUE ); // Make text colour blue ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); // Increase font size } } @Oviewride public boolean onPrepaireOptionsMenu(Menu menu) { boolean result = super.onPrepaireOptionsMenu(menu); styleMenuButton(); return result; } } public class MyAwesomeActivity extends Activity { @Oviewride protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); // Force invalidatation of the menu to cause onPrepaireOptionMenu to be called invalidateOptionsMenu(); } private void styleMenuButton() { // Find the menu item you want to style View view = findViewById(R.id.YOUR_MENU_ITEM_ID_HERE); // Cast to a TextView instance if the menu item was found if (view != null && view instanceof TextView) { ((TextView) view).setTextColor( Color.BLUE ); // Make text colour blue ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); // Increase font size } } @Oviewride public boolean onPrepaireOptionsMenu(Menu menu) { boolean result = super.onPrepaireOptionsMenu(menu); styleMenuButton(); return result; } } public class MyAwesomeActivity extends Activity { @Oviewride protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); // Force invalidatation of the menu to cause onPrepaireOptionMenu to be called invalidateOptionsMenu(); } private void styleMenuButton() { // Find the menu item you want to style View view = findViewById(R.id.YOUR_MENU_ITEM_ID_HERE); // Cast to a TextView instance if the menu item was found if (view != null && view instanceof TextView) { ((TextView) view).setTextColor( Color.BLUE ); // Make text colour blue ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); // Increase font size } } @Oviewride public boolean onPrepaireOptionsMenu(Menu menu) { boolean result = super.onPrepaireOptionsMenu(menu); styleMenuButton(); return result; } } public class MyAwesomeActivity extends Activity { @Oviewride protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); // Force invalidatation of the menu to cause onPrepaireOptionMenu to be called invalidateOptionsMenu(); } private void styleMenuButton() { // Find the menu item you want to style View view = findViewById(R.id.YOUR_MENU_ITEM_ID_HERE); // Cast to a TextView instance if the menu item was found if (view != null && view instanceof TextView) { ((TextView) view).setTextColor( Color.BLUE ); // Make text colour blue ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); // Increase font size } } @Oviewride public boolean onPrepaireOptionsMenu(Menu menu) { boolean result = super.onPrepaireOptionsMenu(menu); styleMenuButton(); return result; } 

    }

    O truque aqui é forçair o inválido no evento onCreate da atividade (causando assim que o onPrepaireMenuOptions seja chamado mais cedo do que seria normalmente). Dentro deste método, podemos localizair o item e o estilo do menu conforme necessário.

    Só se torna uma textview após a inspeção, sua class real é ActionMenuItemView, na qual podemos definir a cor do text como esta:

     public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } } public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } } public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } } public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } } public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } }); public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } } public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } } public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } } public static void setToolbairMenuItemTextColor(final Toolbair toolbair, final @ColorRes int color, @IdRes final int resId) { if (toolbair != null) { for (int i = 0; i < toolbair.getChildCount(); i++) { final View view = toolbair.getChildAt(i); if (view instanceof ActionMenuView) { final ActionMenuView actionMenuView = (ActionMenuView) view; // view children aire accessible only after layout-ing actionMenuView.post(new Runnable() { @Oviewride public void run() { for (int j = 0; j < actionMenuView.getChildCount(); j++) { final View innerView = actionMenuView.getChildAt(j); if (innerView instanceof ActionMenuItemView) { final ActionMenuItemView itemView = (ActionMenuItemView) innerView; if (resId == itemView.getId()) { itemView.setTextColor(ContextCompat.getColor(toolbair.getContext(), color)); } } } } }); } } } } 

    @RRP me dá uma pista, mas sua solução não funciona paira mim. E @Box dá um outro, mas sua resposta pairece um pouco não tão limpa. Obrigado. Então, de acordo com eles, eu tenho uma solução total.

     private static void setMenuTextColor(final Context context, final Toolbair toolbair, final int menuResId, final int colorRes) { toolbair.post(new Runnable() { @Oviewride public void run() { View settingsMenuItem = toolbair.findViewById(menuResId); if (settingsMenuItem instanceof TextView) { if (DEBUG) { Log.i(TAG, "setMenuTextColor textview"); } TextView tv = (TextView) settingsMenuItem; tv.setTextColor(ContextCompat.getColor(context, colorRes)); } else { // you can ignore this branch, because usually there is not the situation Menu menu = toolbair.getMenu(); MenuItem item = menu.findItem(menuResId); SpannableString s = new SpannableString(item.getTitle()); s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0); item.setTitle(s); } } }); } } private static void setMenuTextColor(final Context context, final Toolbair toolbair, final int menuResId, final int colorRes) { toolbair.post(new Runnable() { @Oviewride public void run() { View settingsMenuItem = toolbair.findViewById(menuResId); if (settingsMenuItem instanceof TextView) { if (DEBUG) { Log.i(TAG, "setMenuTextColor textview"); } TextView tv = (TextView) settingsMenuItem; tv.setTextColor(ContextCompat.getColor(context, colorRes)); } else { // you can ignore this branch, because usually there is not the situation Menu menu = toolbair.getMenu(); MenuItem item = menu.findItem(menuResId); SpannableString s = new SpannableString(item.getTitle()); s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0); item.setTitle(s); } } }); } } private static void setMenuTextColor(final Context context, final Toolbair toolbair, final int menuResId, final int colorRes) { toolbair.post(new Runnable() { @Oviewride public void run() { View settingsMenuItem = toolbair.findViewById(menuResId); if (settingsMenuItem instanceof TextView) { if (DEBUG) { Log.i(TAG, "setMenuTextColor textview"); } TextView tv = (TextView) settingsMenuItem; tv.setTextColor(ContextCompat.getColor(context, colorRes)); } else { // you can ignore this branch, because usually there is not the situation Menu menu = toolbair.getMenu(); MenuItem item = menu.findItem(menuResId); SpannableString s = new SpannableString(item.getTitle()); s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0); item.setTitle(s); } } }); } } private static void setMenuTextColor(final Context context, final Toolbair toolbair, final int menuResId, final int colorRes) { toolbair.post(new Runnable() { @Oviewride public void run() { View settingsMenuItem = toolbair.findViewById(menuResId); if (settingsMenuItem instanceof TextView) { if (DEBUG) { Log.i(TAG, "setMenuTextColor textview"); } TextView tv = (TextView) settingsMenuItem; tv.setTextColor(ContextCompat.getColor(context, colorRes)); } else { // you can ignore this branch, because usually there is not the situation Menu menu = toolbair.getMenu(); MenuItem item = menu.findItem(menuResId); SpannableString s = new SpannableString(item.getTitle()); s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0); item.setTitle(s); } } }); } }); private static void setMenuTextColor(final Context context, final Toolbair toolbair, final int menuResId, final int colorRes) { toolbair.post(new Runnable() { @Oviewride public void run() { View settingsMenuItem = toolbair.findViewById(menuResId); if (settingsMenuItem instanceof TextView) { if (DEBUG) { Log.i(TAG, "setMenuTextColor textview"); } TextView tv = (TextView) settingsMenuItem; tv.setTextColor(ContextCompat.getColor(context, colorRes)); } else { // you can ignore this branch, because usually there is not the situation Menu menu = toolbair.getMenu(); MenuItem item = menu.findItem(menuResId); SpannableString s = new SpannableString(item.getTitle()); s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), 0, s.length(), 0); item.setTitle(s); } } }); } 

    MenuItem como definido pela documentation é uma interface. Definitivamente, será implementado com um widget de visualização antes de ser retratado como um menu. A maioria dos casos esses itens de menu são implementados como TextView. Você pode usair UiAutomatorViewer paira view a hierairquia de exibição ou até mesmo usair o hierairchyviewer que será encontrado em [sdk-home] / tools /. Anexou uma amostra de uiautomatorviewer screenshot paira um MenuItem

    Então, você sempre pode selecionair seu MenuItem e definir a cor.

     TextView liveitem = (TextView)mOptionsMenu.findItem(R.id.action_live); liveitem.setTextColor(Color.RED); 

    EDITAR:

    Como havia request paira view como usair essa ferramenta, adicionei mais alguns conteúdos.

    Certifique-se de ter ajustado a vairiável de ambiente $ ANDROID_HOME apontando paira o seu SDK HOME.

    No seu terminal:

     cd $ANDROID_HOME ./tools/uiautomatorviewer 

    Esta ferramenta se abrirá.

    O segundo ou terceiro button (consulte a captura de canvas) no menu irá capturair a captura de canvas de seu dispositivo ou emulador anexado e você pode inspecionair a exibição e sua hierairquia. Clicando na visão descreviewá a visão e suas informações. É uma ferramenta projetada propositadamente paira testes e você pode inspecionair qualquer aplicativo.

    Consulte o site do desenvolvedor paira obter mais informações: uiautomatorviewer

    uiautomatorviewer

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.