片段,RecyclerView:未连接适配器;跳过布局

时间:2018-11-04 00:45:41

标签: android android-recyclerview

我正在使用一个片段来查看RecyclerView。但是我总是会收到此错误

  

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

我为我的recyclerview创建了一个适配器,但是布局不显示。 php后端工作正常。有人可以帮忙吗?这是我的片段和适配器代码

Tips.java

public class Tips extends Fragment {

Configuration config = new Configuration();
String HttpUrl = config.viewtips_url;
List<TipModel> tipList;
RecyclerView recyclerView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_tips, container, false);
    recyclerView = view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    tipList = new ArrayList<>();
    loadTips();
    return view;
}

private void loadTips() {
    StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            tipList.add(new TipModel(
                                    jsonObject.getInt("id"),
                            jsonObject.getString("tip")

                            ));
                        }
                        TipAdapter tipAdapter = new TipAdapter(getActivity(), tipList);
                        recyclerView.setAdapter(tipAdapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
    Volley.newRequestQueue(getActivity()).add(stringRequest);
}

TipAdapter.java

public class TipAdapter extends RecyclerView.Adapter<TipAdapter.TipViewHolder> {

private Context context;
private List<TipModel> tipList;

public TipAdapter(Context context, List<TipModel> tipList) {
    this.context = context;
    this.tipList = tipList;
}

@Override
public TipViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.itemlayout, null);
    return new TipViewHolder(view);
}

@Override
public void onBindViewHolder(TipViewHolder holder, int position) {
    TipModel tipModel = tipList.get(position);


    holder.textViewTip.setText(tipModel.getTip());

}

@Override
public int getItemCount() {
    return tipList.size();
}

class TipViewHolder extends RecyclerView.ViewHolder {
    TextView textViewTip;

    public TipViewHolder(View view) {
        super(view);
        textViewTip = view.findViewById(R.id.textViewTip);
    }
}

3 个答案:

答案 0 :(得分:0)

发生这种情况是因为RecyclerView在分配在创建的视图上的布局时需要适配器,因此,如果在创建视图时没有适配器,那就很好了,它会跳过布局部分。

如果您担心该错误,则可以在创建视图时设置一个空适配器:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_tips, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    recyclerView = view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    tipList = new ArrayList<>();
    recyclerView.setAdapter(new TipAdapter(getActivity(), tipList));
}

然后在响应回调中调整代码:

@Override
public void onResponse(String response) {

    // Instead of setting adapter here...
    // TipAdapter tipAdapter = new TipAdapter(getActivity(), tipList);
    // recyclerView.setAdapter(tipAdapter);

    // Just notify the adapter that tipList has changed.
    recyclerView.getAdapter().notifyDataSetChanged();

    // ...
}

答案 1 :(得分:0)

TipList是适配器的数据存储,它属于适配器而不是片段

我已经编辑了您的代码(无法访问Android Studio,请在文本编辑器中进行操作,请检查语法错误)

片段

public class Tips extends Fragment {

Configuration config = new Configuration();
String HttpUrl = config.viewtips_url;

RecyclerView recyclerView;
TipAdapter tipAdapter;

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

    // Initialize the Tip Adapter
    tipAdapter = new TipAdapter(getActivity());

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_tips, container, false);
    recyclerView = view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    // Assign the Adapter to recyclerView
    recyclerView.setAdapter(tipAdapter);

    return view;
}

private void loadTips() {
    StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        // Create a new TipList
                        List<TipModel> tipList = new ArrayList<>();

                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            tipList.add(new TipModel(
                                jsonObject.getInt("id"),
                                jsonObject.getString("tip")
                            ));
                        }

                        tipAdapter.updateWith(tipList)

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
    Volley.newRequestQueue(getActivity()).add(stringRequest);
}

TipAdapter

public class TipAdapter extends RecyclerView.Adapter<TipAdapter.TipViewHolder> {

private Context context;
private List<TipModel> tipList = new ArrayList<>();

public TipAdapter(Context context) {
    this.context = context;
}

@Override
public TipViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.itemlayout, null);
    return new TipViewHolder(view);
}

@Override
public void onBindViewHolder(TipViewHolder holder, int position) {
    TipModel tipModel = tipList.get(position);


    holder.textViewTip.setText(tipModel.getTip());

}

@Override
public int getItemCount() {
    return tipList.size();
}

class TipViewHolder extends RecyclerView.ViewHolder {
    TextView textViewTip;

    public TipViewHolder(View view) {
        super(view);
        textViewTip = view.findViewById(R.id.textViewTip);
    }
}

public updateWith(List<TipModel> tipList) {
    this.tipList = tipList;
    notifyDataSetChanged();
}

答案 2 :(得分:0)

当在片段中扩大回收站视图时遇到类似问题时,这就是我的方法。这段代码对我来说是完美的:

P.S。 -这是我在应用程序中使用的代码补丁。不便之处,敬请谅解。

首先,在显示片段的onCreateView()中:

render() {

const array = [];
this.state.fillingStations.map((item, index) => (

  array.push(<Parent key={index} title={index + 1} status='' />),

  this.state.fillingChildren.map((it, ind) => {

    if (item.name === it.name) {

      parent.splice(index, 1,
        <Parent {...this.props}}>
          <Child {...this.props} />
        </Parent >);
    }
  })

));

return (
  <div className='row'>
    {array}
  </div>
);

然后,我们调用onStart()。这是因为在将适配器设置为onCreateView()之前,回收站视图通常不会膨胀。

public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        Firebase.setAndroidContext(getActivity());
        ((Home_Drawer) getActivity())
                .setActionBarTitle("Home");

        recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view_home_frag);
        progressBar = (ProgressBar) root.findViewById(R.id.mainPageProgressBar);

//        Log.i("inside", "rv initiated" +mLayoutManager.toString());
        // Assign activity this to progress dialog.
        progressDialog = new ProgressDialog(getActivity());

        // Setting up message in Progress dialog.
        progressDialog.setMessage("Loading Images From Firebase.");
        // Showing progress dialog.
        progressDialog.show();
        // The path is already defined in MainActivity.
        databaseReference = FirebaseDatabase.getInstance().getReference().child("productDisplay");
        Log.i("inside", databaseReference.toString());

        return root;
    }

这对我来说非常有效。希望它能解决您的问题。