首先为您希望导航抽屉看起来像这样创建一个 nav_view:
nav_drawer.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">
<include
android:id="@+id/header"
layout="@layout/your_nav_header"
android:layout_width="match_parent"
android:layout_height="176dp"/>
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/tvVersion"
android:layout_below="@+id/header">
<LinearLayout
android:id="@+id/dynamically_added_items"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="vertical"/>
</ScrollView>
</RelativeLayout>
那么在你看来:
val li = LayoutInflater.from(context)
val mainView = li.inflate(R.layout.nav_drawer, null)
val linearLayout = mainView.findViewById<LinearLayout>(R.id.dynamically_added_items)
items.forEach {
val navItem = MyNavigationItem(li)
linearLayout.addView(navItem.getView())
}
哪些项目是您要添加到抽屉中的项目列表,这可以是一个列表或只是一个项目,如下所示:
val navItem = MyNavigationItem(li)
linearLayout.addView(navItem.getView())
其中 MyNavigationItem 是一个用于设置抽屉中每个项目的视图的类:
class NavigationItemWidget(
item: MyItem,
li: LayoutInflater
) {
private val mainView = li.inflate(R.layout.item_nav, null)
fun getView(): View {
mainView.setOnClickListener {
}
}
}
在上述类中,通过 getView() 函数为您的自定义 item_nav 布局设置视图。