Как добавить пользовательский элемент в NavigationView с макетом меню?

Я использую тег actionLayout, но он перемещает все вправо. Может кто-нибудь посоветовать, почему это происходит. Я тоже пробовал с разными значками и тот же результат.

Activity_main.xml

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

activity_main_drawer.xml

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

        <item
            android:id="@+id/nav_saved_deals"
            android:icon="@drawable/ic_attach_money_black_24dp"
            android:title="Saved Deals" />
        <item
            android:id="@+id/nav_settings"
            android:icon="@mipmap/perm_group_system_tools"
            android:title="Settings" />
    </group>

    <item android:title="Communicate">
        <menu>

            <item
                android:id="@+id/nav_fb_share"
                android:title=""
                app:actionLayout="@layout/fb_menu_item" />
            <item
                android:id="@+id/nav_share_other"
                android:icon="@drawable/ic_menu_share"
                android:title="Share other" />

        </menu>
    </item>
</menu>

fb_menu_item.xml

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

    <ImageView
        android:id="@+id/icon"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:src="@mipmap/facebook" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/icon"
        android:layout_toRightOf="@+id/icon"
        android:gravity="center_vertical"
        android:text="Line 1"
        android:textColor="#000"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/subTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"            
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/icon"
        android:text="Line 2" />

</RelativeLayout>

введите здесь описание изображения

Макет отображается в верхнем левом углу экрана над строкой состояния.

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main">
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="wrap_content">

            <include
                layout="@layout/fb_menu_item"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>

       </android.support.design.widget.NavigationView>

person llBuckshotll    schedule 15.02.2016    source источник
comment
Аналогичный вопрос для ясности. Заголовок stackoverflow.com/questions/30728842/   -  person llBuckshotll    schedule 17.02.2016


Ответы (2)


Как правило, actionLayout необходим для установки вида действия (а не всего элемента), и он всегда выравнивается по правой стороне. И я не уверен, что это выравнивание может быть изменено. Здесь вы можете найти дополнительную информацию об этом https://developer.android.com/guide/topics/resources/menu-resource.html

Что касается пользовательских элементов, насколько я знаю, было бы лучше использовать NavigationView следующим образом:

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include layout="@layout/nav_header" />

        ... listview/linearlayout/just items ...

    </LinearLayout>
</android.support.design.widget.NavigationView>

Я только что попробовал это решение - и оно работает:

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/header"
            android:layout_width="match_parent"
            android:layout_height="172dp"
            android:background="@drawable/drawer_background"
            android:orientation="horizontal">
        </LinearLayout>

        <RelativeLayout 
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/icon"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:src="@drawable/ic_add_black" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toEndOf="@+id/icon"
                android:layout_toRightOf="@+id/icon"
                android:gravity="center_vertical"
                android:text="Line 1"
                android:textColor="#000"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/subTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_toRightOf="@+id/icon"
                android:text="Line 2" />

        </RelativeLayout>
    </LinearLayout>
</android.support.design.widget.NavigationView>
person Sergey Trukhachev    schedule 15.02.2016
comment
Это добавит пользовательские элементы в верхний левый угол экрана над строкой состояния. - person llBuckshotll; 17.02.2016
comment
Та же сделка. Всегда вверху экрана - person llBuckshotll; 17.02.2016
comment
Попробовал на своей машине - работает. Проверьте мое обновление для кода. - person Sergey Trukhachev; 18.02.2016
comment
Да, дополнительный LinearLayout переместит пользовательский элемент вниз, но он больше не является частью исходного меню. Этого можно избежать, добавив сюда все пункты меню. Но действительно ли это лучший ответ? Потому что макеты просто перекрывают исходные макеты меню. И откуда 172dp? Это всегда высота headerLayout? - person llBuckshotll; 19.02.2016
comment
Я нашел высоту, она была определена как 160. - person llBuckshotll; 19.02.2016
comment
172dp — это значение по умолчанию для заголовка в соответствии с руководством по дизайну материалов, но оно не является обязательным, и вы можете свободно изменять его в соответствии с вашими потребностями. - person Sergey Trukhachev; 19.02.2016

Попробуй это

public void addItem(){
     MenuItem mainItem = navigationView.getMenu().findItem(R.id.Communicate);
     SubMenu subMenu = mainItem.getSubMenu();
     subMenu.add(R.id.Communicate, Menu.NONE, Menu.NONE, "Share to Facebook").setIcon(context.getResources().getDrawable(R.drawable.facebook, context.getTheme()));
}
person Vassilis Pallas    schedule 15.02.2016
comment
Это просто добавляет пункт меню. Он не добавляет пользовательский элемент. - person llBuckshotll; 17.02.2016