Добавить разделитель между NavigationViews

Мне нужно добавить разделитель между двумя NavigationViews в моем приложении. (navigation_drawer_top и navigation_drawer_bottom).

Я пробовал это. Но это добавило разделителя к верхней части представления. не в конце первого NavigationView(navigation_drawer_top).

<View android:layout_width="match_parent"
          android:layout_height="1dp"
          android:background="?android:attr/listDivider"/>

Вот мой код

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

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

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

        <android.support.design.widget.NavigationView
            android:id="@+id/navigation_drawer_top"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="top"
            android:background="@color/menuColor"
            android:paddingLeft="50dp"
            app:headerLayout="@layout/nav_header_main"
            app:itemTextAppearance="@style/NavigationDrawerStyle"
            app:itemTextColor="@color/menuTextColour"
            app:menu="@menu/menu_navigation_drawer_top"
            />

        <android.support.design.widget.NavigationView
            android:id="@+id/navigation_drawer_bottom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/menuColor"
            android:layout_gravity="bottom"
            android:paddingLeft="50dp"
            app:itemTextAppearance="@style/NavigationDrawerStyle"
            app:itemTextColor="@color/menuTextColour"
            app:menu="@menu/menu_navigation_drawer_bottom" />

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

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

person Bishan    schedule 14.03.2017    source источник
comment
Вам нужно создать макет navigation_drawer_bottom и разделитель в верхней части макета. Попробуйте и дайте мне знать в случае беспокойства.   -  person Ravindra Kushwaha    schedule 14.03.2017
comment
stackoverflow.com/questions/30605286 /   -  person Komal12    schedule 14.03.2017


Ответы (2)


попробуй это

<View
android:layout_below="@+id/id_of_item_below_which_you_want_it"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?android:attr/listDivider"/>
person AwaisMajeed    schedule 14.03.2017

Это довольно просто сделать. Все, что вам нужно сделать, это создать группу и присвоить группам уникальный идентификатор. Уникальный идентификатор — это то, что помогает добавить разделитель в ваше меню.

Вот краткий пример для вас,

<group android:id="@+id/group1" android:checkableBehavior="single" >
    <item
        android:id="@+id/item_1"
        android:checked="true"
        android:icon="@drawable/ic_1"
        android:title="@string/title_1" />
</group>

<group android:id="@+id/group2" android:checkableBehavior="single" >
    <item
        android:id="@+id/item_2"
        android:icon="@drawable/ic_2"
        android:title="@string/title_2" />
</group>

Это, несомненно, добавит разделителей в ваши меню.

EDIT Поскольку вы добавляете меню программно, вам следует попытаться получить доступ к каждому NavigationMenuView и добавить к ним декоратор.

NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
NavigationMenuView navMenuView = (NavigationMenuView) navigationView.getChildAt(0);
navMenuView.addItemDecoration(new DividerItemDecoration(appContext,DividerItemDecoration.VERTICAL_LIST))

И вот вам DividerItemDecoration класс,

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}
person Aritra Roy    schedule 14.03.2017
comment
Пробовал это. но не работал. У меня только group с моим меню. Я добавляю элементы динамически. - person Bishan; 14.03.2017
comment
Затем вам нужно динамически создавать группы с уникальными идентификаторами. Я использую это в своем приложении, и оно работает достаточно хорошо. - person Aritra Roy; 14.03.2017
comment
Ваша проблема с этим решена? Вам нужна еще помощь? - person Aritra Roy; 14.03.2017
comment
Все равно не повезло. Не могли бы вы описать, как динамически создавать группы с уникальными идентификаторами? - person Bishan; 14.03.2017
comment
Знаете ли вы количество элементов навигации, которые хотите добавить? - person Aritra Roy; 14.03.2017
comment
Нет. Это динамично. Данные поступают из веб-сервиса. - person Bishan; 15.03.2017