Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.widget.textview cannot be applied to android.view.view

Tags:

android

I'm trying to follow the Android official doc for Creating Lists and Cards.

In the third (from the top) code example in the page, there's an example on how to implement MyAdapter which provides access to the items in the dataset, creates views for items and replaces them when their no longer visible.

Problem is, on onCreateViewHolder they pass v which is a View to the ViewHolder which is implemented just before that. The constructor of the ViewHolder expects a TextView. Android Studio 1.0 than shouts:

android.widget.textview cannot be applied to android.view.view

What's wrong?

like image 518
user1555863 Avatar asked Dec 12 '14 19:12

user1555863


1 Answers

This is the new RecyclerView Pattern. In it, you use 3 components:

ViewHolder object which extends RecyclerView.ViewHolder. In it, you define View fields and a constructor which accepts a View v as parameter. in this constructor, use v.findViewById() to bind all these views

onCreateViewHolder() does two things - first you inflate a View object from a layout. Then you create a ViewHolder (one you defined above) with this inflated View passed as parameter.

Finally, onBindViewHolder() is passed a ViewHolder object, in which you put contents into all the fields defined in the first and bound in the third step.

As for the example you mentioned, there is a mistake. The onCreateViewHolder() method should look like this:

// 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((TextView)v);  //You need a cast here
    return vh;
}

OR the ViewHolder should define a constructor expecting a View object (this is actually more correct):

public static class ViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case
    public TextView mTextView;
    public ViewHolder(View v) {            
        mTextView = (TextView) v.findViewById(/* some ID */);
    }
}
like image 133
Kelevandos Avatar answered Oct 19 '22 16:10

Kelevandos