如何在 android 支持设计库中自定义 NavigationView 项?例如,我想自定义项目的文本视图或项目的图像视图我想为导航视图列表的每一行添加 xml 布局,例如 ListView 适配器。请帮我。
问问题
1132 次
1 回答
1
您可以完全为导航视图创建自定义视图。在下面的示例中,我在导航视图中使用片段容器,然后根据需要自定义片段。
在您的活动布局中
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view_controllers.diagrams.DiagramEditorScreen"
android:id="@+id/diagramEditorMainDrawerLayout"
>
.... {your activity layout}
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="@+id/diagramEditorSlideInMenuNavigationView"
app:itemTextColor="@color/white"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/diagramEditorSlideInMenuFragmentHolder"
>
</FrameLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
我在 navigationView 中使用的片段布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/tools"
android:textAllCaps="true"
android:gravity="start"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="2dp"
android:layout_marginEnd="10dp"
android:fontFamily="@font/trade_gothic_next_lt_pro_bd"
android:textColor="@color/mediumGray"
android:textSize="16sp"
/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@color/mediumGray"
android:layout_marginStart="10dp"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/fragmentBrushesRecyclerView"
android:layout_weight="1"
android:layout_marginTop="10dp"
>
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
在您的 ActivityonCreate
方法中添加侦听器
val actionDrawerToggle = ActionBarDrawerToggle(this, diagramEditorMainDrawerLayout, R.string.open, R.string.close)
diagramEditorMainDrawerLayout.addDrawerListener(actionDrawerToggle)
actionDrawerToggle.syncState()
当您准备好显示 navigationView 时,您只需替换 navigationView 和openDrawer()
. 我使用此功能将 navigationView 替换为几个不同的片段。
supportFragmentManager.beginTransaction()
.replace(R.id.diagramEditorSlideInMenuFragmentHolder, {your-fragment}, {your-fragment-tag})
.commit()
diagramEditorMainDrawerLayout.openDrawer(GravityCompat.START)
注意:以上是用 androidX 完成的。如果您不使用 androidX,则对 navigationView 的布局调用应该是
<android.support.v4.widget.DrawerLayout
....
>
<android.support.design.widget.NavigationView
...
/>
</android.support.v4.widget.DrawerLayout>
于 2019-09-24T17:53:33.057 回答