android - 如何使用菜单布局将自定义项添加到 NavigationView?

标签 android navigation-drawer

我一直在尝试通过使用新的 NavigationView 来简化一些抽屉导航代码。 Android 设计支持库中的类。如果您只想要左侧的图标和右侧的文本(如文档中的示例),它会很好用,但是如果我想向具有 android.support.v7 的布局添加单个自定义 View 怎么办.widget.SwitchCompat 就像在 Google Play 电影应用中一样(见下面的截图)?

Google Play Movies

我尝试使用 actionLayout 属性来指定自定义布局文件,如下面的示例代码所示,但是该属性似乎被忽略了,因为它不起作用。

res/menu/navigation_drawer.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/group1"
            android:checkableBehavior="single">
        <item
            android:id="@+id/nav_screen1"
            android:icon="@drawable/ic_list_black_24dp"
            android:title="Screen 1" />
        <item
            android:id="@+id/nav_screen2"
            android:icon="@drawable/ic_search_black_24dp"
            android:title="Screen2"/>
    </group>
    <group  android:id="@+id/group2">
        <item
            android:id="@+id/nav_custom"
            android:icon="@drawable/custom_icon_24dp"
            app:actionLayout="@layout/nav_drawer_switch"
            android:title="Custom item with switch"/>
        <item
            android:id="@+id/nav_settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="Settings"/>
    </group>
</menu>

res/layout/nav_drawer_switch.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.SwitchCompat
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:text="Custom item with switch"/>
</LinearLayout>

我怎样才能让它工作?理想情况下,我想在仍然使用我的菜单布局的同时添加自定义 View ,但如果不使用粗略的 hack(比如利用支持库生成的现有布局)就不可能做到这一点,那么我想知道代码量最少的解决方案,仍然值得转换到 NavigationView

最佳答案

actionLayout 属性为 now supported in Android Support Library 23.1 :

NavigationView provides a convenient way to build a navigation drawer, including the ability to creating menu items using a menu XML file. We’ve expanded the functionality possible with the ability to set custom views for items via app:actionLayout or using MenuItemCompat.setActionView().

所以问题中的代码现在应该可以工作了。

关于android - 如何使用菜单布局将自定义项添加到 NavigationView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30728842/

相关文章:

java - 如何在android中的另一个类中使用方法的返回值

java - Android 中的 TextView.setText

android - 像 Support NavigationView 中的图标着色

滑动抽屉内的 Android 选项卡

Android:NavigationDrawer/多个 Activity/相同的菜单

android - 无法在 Android 上滚动 AutoCompleteTextView 的下拉列表

Android - 通过 HTTPS 进行渐进式下载

java - 通过 ImageView onClick 打开在 HomeFragment 的 MainActivity 中创建的 DrawerLayout 并避免 NPE

android - 旋转动画在 Jetpack Compose 中不起作用

android - 如何正确使用 Navigation Drawer 中的 ListView