首页 > 解决方案 > 导航抽屉未使用 RecyclerView 加载布局

问题描述

我有我的 Events.java 和 event.xml 布局,如果我直接加载 Event 类,它有一个回收器视图&工作正常。它看起来像这样:

带有 RecyclerView 的 events.xml

但是,如果我加载导航抽屉,然后加载 event.xml 文件,则会出现以下屏幕并显示此错误:“未连接适配器;跳过布局”。

在此处输入图像描述

我的问题是为什么导航菜单不起作用并且事件布局文件没有加载?至于我的代码,我认为以下内容可能会有所帮助。

事件.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    RecyclerView recyclerView = findViewById(R.id.events_rv_list);
    EventsAdapter eventsAdapter = new EventsAdapter(this, eList, this);

    recyclerView.setAdapter(eventsAdapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
}

事件.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Events"
    android:background="#ffff6c">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/events_rv_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>

NavigationDrawer.java

    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.navigation_drawer);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
    }
    ...

标签: javaandroid

解决方案


好的,我找到了解决方案。错误是适配器未附加到 RecyclerView。

在第一张图片中,适配器工作,因为它存储在普通布局文件(非片段)类中,因此从 events.java 调用 onCreate。Events.java 然后加载布局 (events.xml) 并将适配器附加到 RecyclerView,如下所示:

RecyclerView recyclerView = view.findViewById(R.id._events_recyclerview);

ADAPTE_CLASS adapter = new ADAPTE_CLASS(PASS DATA IF NECESSARY);

recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

现在可以在 Fragment 中应用相同的内容,您可以在其中将上述代码添加到 onCrateView 方法(具有相关的类名和 id)。这就是您在 fragnent 中设置 recyclerview 适配器的方式

希望有帮助。


推荐阅读