我正在尝试关注this教程。
Google提供以下代码:
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;
}
}
我正在尝试将此工作完全作为示例。我创建了一个my_text_view.xml文件,如下所示:
<?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"
/>
但是,我在这一行收到错误:
TextView v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
必需是一个android.widget.TextView并且我给了一个android.view.View
我一定是误解了如何传递textView。通常我会使用(TextView)R.FindViewById,但是当教程从布局中抓取它时,我认为它不希望我这样做。
非常感谢一些帮助理解这一点。
答案 0 :(得分:1)
例子说:
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
但你写了
TextView v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
您无需使用“TextView”更改“View”,只需将其保留为示例中的原样即可。如果在此之后,您收到此行中的错误消息:
ViewHolder vh = new ViewHolder(v);
说:ViewHolder中的ViewHolder(android.widget.TextView)无法应用于(android.view.View)。只需修改如下:
ViewHolder vh = new ViewHolder((TextView)v);
另外:在myDataset中发送多个值,如果你发送一个值,它可能会在工具栏下隐藏。
答案 1 :(得分:0)
方法inflate
返回View
个实例。所以你必须投射到适当的视图。这不是Android
关于Java
。