如何使用 RecyclerView,尝试遵循 developer.android.com 建议但出现错误

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

我正在尝试使用 RecyclerView 来显示我的数据集,试图关注这个网站 https://developer.android.com/training/material/lists-cards.html

问题是有些地方有问题,找不到解决方法,我完全按照那个网站的建议做了。

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'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)
    @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 给我一个错误:

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

我应该怎么做?

好像developer.android.com这里有错别字?

你试过吗?

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

ViewHolder 中的构造函数持有一个TextView。所以你不能将 View 发送给 ViewHolder。尝试像这样将视图缓存到 TextView。

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

当您扩充视图时,创建您正在扩充的特定类型视图的实例通常是个好主意。在这种情况下,您正在给 TextView 充气。由于 TextViewView 扩展,编译器不会抱怨它,但是当您尝试将 View 用作 TextView 时,您的应用程序将崩溃。

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

View 更改为 TextView