简体   繁体   中英

RecyclerView android

when I open app it does not work why?

Why this RecyclerView does not work but I don not why

package com.example.dell.iwantto;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class NameAdapter extends RecyclerView.Adapter<NameAdapter.NameViewHolder> {
    private ArrayList<String> mData;
    public static class NameViewHolder extends RecyclerView.ViewHolder {
        public TextView mNameTextView;
        public NameViewHolder(TextView v) {
            super(v);
            mNameTextView = v;
        }
    }
    public NameAdapter(ArrayList<String> mData) {
        this.mData = mData;
    }

    @Override
    public NameAdapter.NameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        TextView v = (TextView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout,parent, false).findViewById(R.id.xs);
        NameViewHolder vh = new NameViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(NameViewHolder holder, int position) {
        holder.mNameTextView.setText(mData.get(position));
    }

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

How I can solve it ? And what is the error? Why app is stop when I tried to open it in phone?

Your RecyclerView can't work because you're incorrectly giving a child view as a parent view which is needed by ViewHolder in your following code:

@Override
public NameAdapter.NameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    // This is incorrect because the method need a parent view not a child view
    TextView v = (TextView) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.layout,parent, false).findViewById(R.id.xs);
    NameViewHolder vh = new NameViewHolder(v);
    return vh;
}

It should be something like this:

@Override
public NameAdapter.NameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // inflate your layout.
    View view = inflater.inflate(R.layout.layout, parent, false);

    NameViewHolder viewHolder = new NameViewHolder(view);
    return viewHolder;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM