android – 创建时不得附加ViewHolder视图
作者:互联网
我正在尝试创建一个显示TextView的简单RV.
这是我的适配器:
public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.ViewHolder> {
private String[] mDataset;
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;
}
}
public MyRvAdapter(String[] myDataset) {
mDataset = myDataset;
}
@NonNull
@Override
public MyRvAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.text_row_item, parent, false);
TextView userNameInList= v.findViewById(R.id.display_name);
ViewHolder vh = new ViewHolder(userNameInList);
return vh;
}
@Override
public void onBindViewHolder(@NonNull MyRvAdapter.ViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
text_row_item只是一个FrameLayout,里面有一个TextView(“display_name”).
这是恐怖:
java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6687)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5869)
非常感谢你!
解决方法:
实际上,你的ViewHolder期望一个View从R.layout.text_row_item膨胀而不是后者的后代.因此,如果您通过膨胀的视图,问题将得到解决.
所以,你应该纠正你的代码:
public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.ViewHolder> {
private String[] mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public ViewHolder(View v) {
super(v);
mTextView = v.findViewById(r.id.display_name);
}
}
public MyRvAdapter(String[] myDataset) {
mDataset = myDataset;
}
@NonNull
@Override
public MyRvAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.text_row_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(@NonNull MyRvAdapter.ViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
标签:android-viewholder,android,android-recyclerview 来源: https://codeday.me/bug/20190910/1801801.html