【问题标题】:RecyclerView adapter connection error: no adapter attachedRecyclerView 适配器连接错误:未连接适配器
【发布时间】:2019-10-25 23:00:48
【问题描述】:

我想在片段中使用 RecyclerView,但我无法连接适配器。当我运行它时,它失败了,我得到了这个错误

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

片段

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);
    }}

【问题讨论】:

    标签: java android android-recyclerview android-cardview


    【解决方案1】:

    正如您现在所拥有的那样,您正在重新膨胀布局,并返回一个尚未为 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;
    }
    

    【讨论】:

      【解决方案2】:
      你应该返回视图,你膨胀布局并获得recyclerview,你不应该膨胀两次。只返回第一个膨胀视图

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-04
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多