java - RecyclerView适配器连接错误: no adapter attached

标签 java android android-recyclerview android-cardview

我想在 fragment 中使用 RecyclerView,但无法连接适配器。当我运行它时,它失败了并且出现了这个错误

E/RecyclerView:没有连接适配器;跳过布局

Fragment

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;

public class Frag1 extends Fragment {
    private RecyclerView rv;
    private CardAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

      View view =inflater.inflate(R.layout.fragment_frag1, container,false);
        rv= (RecyclerView)view.findViewById(R.id.rv);
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));

        ArrayList<String> words = new ArrayList<>() ;
        words.add("x");
        words.add("x");
        words.add("x");
        adapter= new CardAdapter(getActivity(),words);
        rv.setAdapter(adapter);

        return inflater.inflate(R.layout.fragment_frag1, container, false);
    }}

最佳答案

正如您现在所做的那样,您正在重新扩充布局,并返回一个尚未为 RecyclerView 设置适配器的布局。只需返回您已经充气并用于设置 RecyclerView 的那个:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view =inflater.inflate(R.layout.fragment_frag1, container,false);
    rv= (RecyclerView)view.findViewById(R.id.rv);
    rv.setHasFixedSize(true);
    rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));

    ArrayList<String> words = new ArrayList<>() ;
    words.add("x");
    words.add("x");
    words.add("x");
    adapter= new CardAdapter(getActivity(),words);
    rv.setAdapter(adapter);

    // Return the view that you already inflated:
    return view;
}

关于java - RecyclerView适配器连接错误: no adapter attached,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566669/

相关文章:

android - 在 RecyclerView 项目上添加多个 onClickListener

java - 绑定(bind) View 持有者不在适配器中运行

java - 在 java.io.WinNTFileSystem.createFileExclusively 中摆脱 java.io.Exception 很热吗?

java - Android 使用 WebService,异常 HttpTransportSE.call()

Java 类滥用 - 最佳实践

Android Studio aar 使用 javadoc 进行模糊库发布

javascript - 如何在手机间隙android中打开/关闭面板时停止页面闪烁

java - 如何设置空布局面板内面板的大小?

java - LIbGDX 当语言改变时如何翻译所有文本?

android - 关于RecyclerViews能力的讨论