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

匿名 (未验证) 提交于 2019-12-03 08:35:02

问题:

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?

回答1:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!