Search code examples
androidandroid-layouttextviewcardlayout

Difficulty following Android "Creating List and Cards tutorial"


I am trying to follow this tutorial.

Google give the following code:

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);
        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;
    }
}

I am trying to make this work exactly as the example. I have created a my_text_view.xml file which looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:text="testing"
    />

However, I receive an error on this line:

TextView v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.my_text_view, parent, false);

that Required is a android.widget.TextView and that I have given an android.view.View

I must be misunderstanding how to pass a textView. Usually I would use (TextView) R.FindViewById however as the tutorial is grabbing it from layout I don't think it wants me to do this.

Would really appreciate some help understanding this.


Solution

  • Method inflate returns View instance. So you must cast to appropriate view. It's not about Android it's about Java.