Add items in Navigation Drawer Dynamically

天涯浪子 提交于 2019-12-08 15:15:21

问题


I create Drawer.But I want to set Itemlist of drawer is dynamically.Means get data from database and set as drawerList. Is It Possible? and yes than How?I know static drawer as well.


回答1:


try this :

final Menu menu = navigationView.getMenu();
for (int i = 1; i <= 10; i++) {
   menu.add("Runtime item "+ i);
}



回答2:


Narrow down your search to Navigation Drawer with List view. If you have listview you can manipulate data with adapter.

Check this one example. https://youtu.be/rs4LW3GxOgE




回答3:


YES it is possible this will be your main layout:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/login_drawer"
       >

        <LinearLayout
            android:id="@+id/linearlayout"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
//create you toolbar and include in here
        <include
            layout="@layout/tool_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></include>

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></FrameLayout>

        </LinearLayout>

        <include layout="@layout/drawerlayout" />
    </android.support.v4.widget.DrawerLayout>

and you drawer layout will be like this:

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_linear"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
   </LinearLayout>

now you can create another layout which will be the item of drawer menu ie if its only text then make a layout with only textview else if it is image and text then make the layout accordingly

AND then just add this view(child xml) dynamically by using layoutinflater and adding view in linearlayout like:

linearlayout.addView(childview); 



回答4:


thanks to @Dev

To add the Item dynamically, we can get a Menu object using getMenu() method of NavigationView and then we can add Items into the navigation drawer using that Menu object.

like this :

final Menu menu = navigationView.getMenu();
for (int i = 1; i <= 3; i++) {
   menu.add("Runtime item "+ i);
}

Using SubMenu, we can add a subsection and Items into it.

// adding a section and items into it
final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
for (int i = 1; i <= 2; i++) {
   subMenu.add("SubMenu Item " + i);
}

//



来源:https://stackoverflow.com/questions/40946707/add-items-in-navigation-drawer-dynamically

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