EspeH EspeH - 1 year ago 104
Android Question

How to use RecyclerView, Trying to follow suggestion but get error

I'm trying to use RecyclerView to show my dataset, trying to follow this website

Problem is that there is some part wrong and can't findout how to fix it, I did exactly how that site suggest.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public ViewHolder(TextView v) {
mTextView = v;

// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;

// Create new views (invoked by the layout manager)
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v); // ERROR
return vh;

// Replace the contents of a view (invoked by the layout manager)
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element


// Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
return mDataset.length;

Android Studio gives me an error:

ViewHolder (android.widget.TextView) in ViewHolder cannot be applied
to (android.view.View)

How should I do this?

It seems have some typo here?

Answer Source

When you inflate a view, it's usually a good idea to create an instance of the specific type of view that you are inflating. In this case you are inflating a TextView. Since TextView extends from View the compiler will not complain about it, but when you try to use the View as a TextView your app will crash.

// create a new view
TextView v = (TextView) LayoutInflater.from(parent.getContext())
                       .inflate(R.layout.my_text_view, parent, false);

Change View to TextView.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download