使用操作栏菜单项的自定义模板

时间:2017-04-02 13:51:14

标签: android menu android-actionbar

我正在尝试显示一个文本和图标始终可见的菜单。我已将项目布局定义为以下

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/selectableItemBackground"
    android:clickable="true"
    android:drawableLeft="@drawable/ic_cart"
    android:gravity="center"
    android:orientation="vertical"
    android:text="(0)"
    android:drawablePadding="5dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:textColor="@android:color/white" />

菜单定义如下

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.taptoscan.taptoscan.MainActivity">

    <item
        android:id="@+id/action_sign"
        android:title="(0)"
        app:showAsAction="always|withText"
        app:actionLayout="@layout/menu_sign" />

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

我遇到了在背景上启用涟漪效应的问题。它可以工作,但涟漪效果不是圆形的,喜欢常规的菜单图标。它是方形的,看起来有点难看。在自定义菜单项上实现原生涟漪效果的最佳方法是什么?

编辑:这就是它的样子

enter image description here

1 个答案:

答案 0 :(得分:1)

注意:找到更好的解决方案,请查看修改

我明白了。首先,我创建了一个带圆角的背景绘图,如下所示:

module.exports = {
    entry: __dirname + '/src/index.js',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    }
};

之后,我将TextView的背景设置为上面的drawable。涟漪效果按预期工作,并且在默认菜单项上都是圆形的。

enter image description here

修改

在进一步搞乱自定义菜单项之后,我发现仅使用没有根元素的TextView将导致在单击另一个菜单项然后再单击其后再更改TextView的基线定制的。解决方案使用以下布局

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">

        <padding
            android:bottom="5dp"
            android:left="5dp"
            android:right="5dp"
            android:top="5dp" />

        <corners android:radius="5dp" />

    </shape>
</ripple>