2016-01-05 4 views
0

Как изменить цвет фона элемента действия меню на панели инструментов?Изменить панель инструментов действие элемент цвет фона

<?xml version="1.0" encoding="utf-8"?> 
<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:edo="http://schemas.android.com/apk/res-auto"> 

    <item 
     android:id="@+id/my_action" 
     android:icon="@mipmap/icon" 
     android:title="@string/title" 
     app:showAsAction="always" /> 
</menu> 

Тогда в моей деятельности:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.menu_actions, menu); 

    final MenuItem item = menu.findItem(R.id.my_action); 

    MenuItemCompat.getActionView(item).setBackgroundColor(ContextCompat.getColor(this, R.color.red)); 

    return super.onCreateOptionsMenu(menu); 

} 

Это не работает, потому что getActionView всегда возвращает нуль.

ответ

0

Здесь мы идем:

public void changeActionMenuItemsBackground(int color) { 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    for (int i = 0; i < toolbar.getChildCount(); i++) { 
     final View v = toolbar.getChildAt(i); 
     if (v instanceof ActionMenuView) { 
      v.setBackgroundColor(color); 
     } 
    } 
} 

Вы можете назвать это прямо в onCreateOptionsMenu() или позже

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    changeActionMenuItemsBackground(Color.BLACK); 
    return true; 
} 

Я надеюсь, что это помогает

0

getActionView() работает, когда есть заказ ActionView из setActionView() в моем случае.

Создание макета и установить его в качестве вида действия для вашего пункта меню, как это:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.new_menu, menu); 
    MenuItem item = menu.findItem(R.id.my_action); 
    View myView = LayoutInflater.from(this).inflate(R.layout.menu_item_layout, null); 
    ((ImageView) myView.findViewById(R.id.btnEdit)).setOnClickListener(this); 
    item = MenuItemCompat.setActionView(item, myView); 
    MenuItemCompat.getActionView(item).setBackgroundColor(ContextCompat.getColor(this, R.color.blue)); 
    return true; 
} 

menu_item_layout.xml:

<?xml version="1.0" encoding="utf-8"?> 
<ImageView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/btnEdit" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:background="@color/red" 
android:minHeight="0dp" 
android:minWidth="0dp" 
android:src="@drawable/img_edt" /> 

Как это вы можете установить цвет либо в getActionView (пункт) .setBackgroundColor (..) или в файле menu_item_layout.xml.

Смежные вопросы