Replace Navigation View Item Ripple Effect

佐手、 提交于 2019-12-25 01:46:37

问题


I am attempting to replace what I thought was the default item background of the NavigationView. So I created a drawable to replace the background and applied it using the itemBackground attribute.

background_navigation_view_item.xml

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/navigation_item_background_tint">
    <item android:id="@android:id/mask" android:top="4dp" android:bottom="4dp" android:left="8dp" android:right="8dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white"/>
            <corners android:radius="3dp"/>
        </shape>
    </item>
    <item android:top="4dp" android:bottom="4dp" android:left="8dp" android:right="8dp">
        <selector>
            <item android:state_checked="true">
                <shape android:shape="rectangle">
                    <solid android:color="@color/navigation_item_background_tint"/>
                    <corners android:radius="3dp"/>
                </shape>
            </item>
            <item>
                <shape android:shape="rectangle">
                    <solid android:color="@android:color/transparent"/>
                    <corners android:radius="3dp"/>
                </shape>
            </item>
        </selector>
    </item>
</ripple>

The item background drawable looks great when the item is selected ("Selection Controls" is the selected item in the image below). But when the item is being clicked ("Progress Indicators" below) it appears that both the default ripple drawable and the background_navigation_view_item.xml drawable are being used (only a rounded rectangle should be shown, not the rectangle surrounding it).

I also tested the drawable as the background of a checkable view, and it works the way I would expect. So if it isn't an error in the code for my drawable, why isn't the original background drawable being replaced?


回答1:


I have already answered this question here

Note: This code just removes the opacity of background default ripple

Anyways, I'll answer it again here.

Assuming your NavigationView code is:

<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/your_menu"
app:itemBackground="@drawable/background_navigation_view_item.xml"/>

What I've done is, added a theme attribute as follows to the NavigationView:

android:theme="@style/NavigationItemNoRipple"

In styles.xml:

<style name="NavigationItemNoRipple">
    <item name="android:colorControlHighlight">@android:color/transparent</item>
</style>


来源:https://stackoverflow.com/questions/55184220/replace-navigation-view-item-ripple-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!