How to use RecyclerView trying to follow .android.com developer suggestion but get error

I am trying to use RecyclerView to display my dataset, trying to follow this website https://developer.android.com/training/material/lists-cards.html

The problem is that some part is incorrect and cannot figure out how to fix it, I did exactly what this site offers.

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) { super(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) @Override 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 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) @Override public void onBindViewHolder(ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element holder.mTextView.setText(mDataset[position]); } // Return the size of your dataset (invoked by the layout manager) @Override 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 can I do it?

Does developer.android.com seem to have a typo here?

+5
source share
3 answers

When you inflate a view, it is usually recommended that you instantiate a specific type of view that you are inflating. In this case, you pump up the TextView . Since TextView continues from View , the compiler will not complain about it, but when you try to use View as a TextView , your application 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 .

+1
source

Have you tried this?

 ViewHolder vh = new ViewHolder((TextView) v); 
+1
source

The constructor in the ViewHolder contains a TextView. Therefore, you cannot submit the View to the ViewHolder. Try caching the view in a TextView like this.

 ViewHolder vh = new ViewHolder((TextView)v); 
0
source

All Articles