2016-08-10 33 views
0

我在android应用中使用上下文菜单来提示用户选择过滤器。相关的代码是:如何指定上下文菜单的背景颜色

TextView someView = (TextView) findViewById(id.some_view); 
registerForContextMenu(someView); 

... 

@Override 
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) 
{ 
    super.onCreateContextMenu(menu, v, menuInfo); 
    menu.setHeaderTitle("Select a Filter"); 

    menu.add(0, 0, 0, "Filter1"); 
    menu.add(0, 1, 1, "Filter2"); 
    menu.add(0, 2, 2, "Filter3"); 
} 

@Override 
public boolean onContextItemSelected(MenuItem item) 
{ 
    if (item.getItemId() == 0) 
    { 
     ... 
    } 
    else 
    { 
     ... 
    } 
    return true; 
} 

在styles.xml文件我用的线:

<item name="android:itemBackground">@color/someColor</item> 

设置option Menu项的背景颜色。我希望它们具有与Actionbar相同的颜色。但效果是,context Menu也采用相同的颜色。

我的问题是我如何为context MenuMenu项目或整个上下文菜单指定背景颜色。有没有办法单独设置它?我是否可以在不影响context Menu的情况下以其他方式设置option Menu项目的背景颜色?

回答

1

可惜你不能自定义快捷菜单,但您可以创建一个Dialog和使用,作为一个ContextMenu .something这样的:

@Override 
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) 
{ 
    final Dialog dialog = new Dialog(this); 
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    dialog.setContentView(R.layout.menu_layout); 

    LinearLayout ll_menu=(LinearLayout)findViewById(R.id.ll_menu); 

    //add some TextView or ImageView to ll_menu as menu items 


    dialog.show(); 
} 

menu_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="match_parent" 
    android:layout_width="match_parent"> 

    <LinearLayout 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/ll_menu" 
    > 


    </LinearLayout> 

</ScrollView>