Android更改弹出菜单的背景颜色

时间:2017-07-27 14:53:49

标签: android background styles popupmenu

我不明白为什么改变Android应用的颜色会如此痛苦。 我尝试了几种方法来改变操作栏中弹出菜单的背景颜色,但没有成功。

我使用AppTheme.NoActionBar来显示动作栏。

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="navigationIcon">@drawable/ic_return_dark</item>
    <item name="overlapAnchor">false</item>
    <item name="popupMenuStyle">@style/PopupMenu</item>
</style>

<style name="PopupMenu" parent="Widget.AppCompat.PopupMenu">
    <item name="android:popupBackground">@color/color4</item>
</style>

根据我找到的示例,有这样的解释,您需要在自定义样式(在我的情况下为 AppTheme.NoActionBar )中插入自定义 popupMenuStyle 自定义 popupBackground ,它会更改弹出菜单的背景颜色。 它没有用。

enter image description here

如何更改弹出菜单的背景颜色?

2 个答案:

答案 0 :(得分:1)

要更改Android中“选项”菜单的颜色,更改主题和样式不会有帮助。您必须初始化LayoutInflater Factory Class。

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.my_menu, menu);
   getLayoutInflater().setFactory(new Factory() {
   @Override
   public View onCreateView(String name, Context context,
   AttributeSet attrs) {
   if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
   try {
   LayoutInflater f = getLayoutInflater();
   final View view = f.createView(name, null, attrs);
   new Handler().post(new Runnable() {
   public void run() {

   view.setBackgroundResource(R.drawable.your_color);

   ((TextView) view).setTextColor(Color.your_color);
   }
   });
   return view;
   } catch (InflateException e) {
   } catch (ClassNotFoundException e) {
   }
   }
   return null;
   }
   });
   return super.onCreateOptionsMenu(menu);
   }

答案 1 :(得分:0)

如果仍然有人想知道是否有更好的解决方案,请参见以下说明和答案。

既然如此,这个问题显然提到使用NoActionBar主题作为应用程序,将popupMenu直接设置为AppTheme无效。

相反,您需要将该主题手动应用于xml中的工具栏

<androidx.appcompat.widget.Toolbar
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  app:popupTheme="@style/PopupMenu" />

并在您的styles.xml文件中

<style name="PopupMenu" parent="Theme.AppCompat.Light">
    <item name="android:textColor">@color/white</item>
    <item name="android:colorBackground">@color/popup_color</item>
</style>
相关问题