recycleview 顶部导航栏
时间: 2023-06-18 13:03:00 浏览: 47
要在 RecyclerView 中添加顶部导航栏,可以将 RecyclerView 和导航栏都包含在一个布局文件中,然后使用 CoordinatorLayout 来协调它们的交互。下面是一个示例布局文件:
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.MaterialComponents.Light" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:clipToPadding="false"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:scrollbars="vertical" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
```
这个布局文件包含了一个 AppBarLayout 和一个 RecyclerView,AppBarLayout 中包含了一个 MaterialToolbar,作为顶部导航栏。AppBarLayout 和 RecyclerView 都被包含在一个 CoordinatorLayout 中。
在代码中,可以像这样获取 RecyclerView 和 Toolbar 的实例:
```java
RecyclerView recyclerView = findViewById(R.id.recycler_view);
MaterialToolbar toolbar = findViewById(R.id.toolbar);
```
然后可以使用 RecyclerView 来显示数据,使用 Toolbar 来添加菜单和处理点击事件等。