为什么我的样式不适用于我的popupMenu?

时间:2016-07-05 06:26:34

标签: android

根据How to style PopupMenu?,您无法直接设置popupmenu样式,这似乎与https://developer.android.com/reference/android/widget/PopupWindow.html相反

它声明您可以在PopupMenu构造函数中指定样式。根据{{​​3}}看起来我需要指定的属性是“android:popupBackground”和“android:dropDownWidth”。但是,以下内容只是删除了默认样式,并没有应用我想要的颜色或宽度:

styles.xml:

<style name="popup">
    <item name="android:popupBackground">@color/material_blue_grey_800</item>
    <item name="android:dropDownWidth">350dp</item>
</style>

ActivityA.java

public class ActivityA extends AppCompatActivity implements    
PopupMenu.OnMenuItemClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_a);
    findViewById(R.id.popupBtn).setOnClickListener(new    
    View.OnClickListener() {
        @Override
        public void onClick(View button) {
            PopupMenu popupMenu = new PopupMenu(ActivityA.this, 
                      button, Gravity.RIGHT, 0, R.style.popup);
        }
    }

@Override
public boolean onMenuItemClick(MenuItem item) {
    return false;
    }
}

activity_a.xml:

<RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:tools="http://schemas.android.com/tools"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:paddingLeft="@dimen/activity_horizontal_margin"
           android:paddingRight="@dimen/activity_horizontal_margin"
           android:paddingTop="@dimen/activity_vertical_margin"
           android:paddingBottom="@dimen/activity_vertical_margin"
           tools:context=".activities.ActivityA">
  <Button
      android:id="@+id/popupBtn"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_alignParentRight="true"
      android:text="Press to open menu"/>
</RelativeLayout>

3 个答案:

答案 0 :(得分:0)

您无法以编程方式应用样式,但可以使用主题执行此操作:https://developer.android.com/guide/topics/ui/themes.html#ApplyAStyle可以在此处找到类似的答案:https://stackoverflow.com/a/2016344/936269

答案 1 :(得分:0)

将此添加到您的AppTheme ..

<item name="android:popupMenuStyle">@style/popup</item>
<item name="popupMenuStyle">@style/popup</item>
祝你好运!

答案 2 :(得分:0)

您可以在主题中声明样式,如下所示:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Other styles -->

        <!-- PopUpMenu styles -->
        <item name="popupMenuStyle">@style/Widget.App.PopupMenu</item>
    </style>

<!-- Widget PopUpMenu Style-->
    <style name="Widget.App.PopupMenu" parent="Widget.AppCompat.Light.PopupMenu">
        <!-- Whatever Styles Put Here-->
    </style>