我关注了android recycler tutorial,我遇到了以下错误
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
at com.ji.www.i.RecycleAdapter.onCreateViewHolder(RecycleAdapter.java:33)
at com.ji.www.i.RecycleAdapter.onCreateViewHolder(RecycleAdapter.java:12)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5288)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4551)
这是代码
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder>{
private String[] mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(TextView v){
super(v);
mTextView=v;
}
}
public RecycleAdapter(String[] myDataset)
{
mDataset =myDataset;
}
@Override
public RecycleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v= LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_textview, parent, false);
ViewHolder vh=new ViewHolder((TextView)v);
return vh;
}
public void onBindViewHolder(ViewHolder holder ,int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount()
{
return mDataset.length;
}
}
这是xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:hint="Insert here" />
</LinearLayout>
答案 0 :(得分:1)
您必须更改ViewHolder
构造函数,以便获得对布局中TextView
的引用。
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder>{
private String[] mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View v){
super(v);
TextView mTextView = (TextView) v.findViewById(R.id.textview);
this.mTextView = mTextView;
}
}
public RecycleAdapter(String[] myDataset)
{
mDataset = myDataset;
}
@Override
public RecycleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v= LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_textview, parent, false);
ViewHolder vh= new ViewHolder(v);
return vh;
}
public void onBindViewHolder(ViewHolder holder ,int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount()
{
return mDataset.length;
}
}