【发布时间】:2018-03-08 17:49:49
【问题描述】:
我创建了抽屉。但我想动态设置抽屉的项目列表。意思是从数据库中获取数据并设置为抽屉列表。可能吗?是的,比 How?我也知道静态抽屉。
【问题讨论】:
-
你想动态加载导航抽屉项目吗?
-
是的。都来自数据库。
我创建了抽屉。但我想动态设置抽屉的项目列表。意思是从数据库中获取数据并设置为抽屉列表。可能吗?是的,比 How?我也知道静态抽屉。
【问题讨论】:
试试这个:
final Menu menu = navigationView.getMenu();
for (int i = 1; i <= 10; i++) {
menu.add("Runtime item "+ i);
}
【讨论】:
是的,这可能是您的主要布局:
<?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>
你的抽屉布局会是这样的:
<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>
现在您可以创建另一个布局,这将是抽屉菜单的项目,即,如果它只有文本,则仅使用 textview 进行布局,否则如果是图像和文本,则相应地进行布局
然后只需使用 layoutinflater 动态添加此视图(子 xml)并在线性布局中添加视图,例如:
linearlayout.addView(childview);
【讨论】:
使用列表视图将搜索范围缩小到导航抽屉。如果您有列表视图,则可以使用适配器操作数据。
检查这个例子。 https://youtu.be/rs4LW3GxOgE
【讨论】:
感谢@Dev
要动态添加 Item,我们可以使用 NavigationView 的 getMenu() 方法获取 Menu 对象,然后我们可以使用该 将 Items 添加到导航抽屉中>菜单对象。
像这样:
final Menu menu = navigationView.getMenu();
for (int i = 1; i <= 3; i++) {
menu.add("Runtime item "+ i);
}
使用 SubMenu,我们可以在其中添加子部分和项目。
// 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);
}
//
【讨论】:
onNavigationItemSelected(MenuItem) 或使用函数Toolbar#setOnMenuItemClickListener(Toolbar.OnMenuItemClickListener),而不是检查该菜单的ID,您可以检查添加该菜单项时分配的标题。