4

我正在使用 ActionBarSherlock。我有一个 MenuItem,我想使用一个只有那个 MenuItem 的自定义选择器,而不是 ActionBar 中的其他选择器。这是菜单代码:

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

    <item
        android:id="@+id/menu_include_location"
        android:icon="@drawable/icon_place_selector"
        android:showAsAction="always"
        android:title="@string/menu_include_location"/>

    <item
        android:id="@+id/menu_send"
        android:icon="@drawable/ic_send"
        android:showAsAction="ifRoom|withText"
        android:title="@string/menu_send"/>

</menu>

这是 icon_place_selector.xml

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

    <item android:drawable="@drawable/location_place" android:state_pressed="false"/>
    <item android:drawable="@drawable/location_no_gradient" android:state_pressed="true"/>

</selector>

问题是在 MenuItem 中,图标只是其中的一小部分。这是显示的屏幕截图。整个背景应该改变,而不仅仅是图标。我怎么做?

在此处输入图像描述

4

3 回答 3

4

您可以通过在代码中设置自定义 ActionView 来更改特定操作栏项的选择器:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.activity_main, menu);
    MenuItem menuItem = menu.findItem(R.id.menu_include_location);
    ImageView image = new ImageView(this);
    image.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));
    image.setPadding(16, 0, 16, 0);
    image.setImageResource(R.drawable.ic_launcher);
    image.setBackgroundResource(R.drawable.icon_place_selector);
    image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // ...
        }
    });
    menuItem.setActionView(image);
    return true;
}

如果要更改所有操作栏项目的选择器,请应用这些样式:

<style name="AppTheme" parent="@style/Theme.Sherlock">
    <item name="android:selectableItemBackground">@drawable/icon_place_selector</item>
    <item name="android:actionBarItemBackground">@drawable/icon_place_selector</item>
</style>
于 2012-11-30T21:04:12.203 回答
1

使用Actionbar 样式生成器,为您的样式设置样式并下载 zip 文件

在下载的 zip 文件中,打开“drawables”文件夹中的 selectable_background_xxxx.xml(xxxx -> 为您自己的样式指定的名称)文件,然后在按下状态为 true 时将可绘制对象更改为您想要的九个补丁 img 或颜色代码。

<item android:state_pressed="true" android:drawable="@color/your_color" /> 
于 2014-01-29T05:18:48.013 回答
1

首先你应该知道,如果你设置android:selectableItemBackground了你的全息样式,整个小部件,即一个按钮,都会有那个背景选择器。

如果您只需要更改操作栏菜单项的图标选择器背景,这里有一个简单的答案!

只需设置android:actionBarItemBackground您的全息样式!

<style name="AppTheme.Dark" parent="android:Theme.Holo">
    <item name="android:actionBarItemBackground">@drawable/item_background_holo_light</item>
</style>

希望它有帮助:-)

于 2014-02-20T14:58:47.847 回答