J'essaie de créer un RV simple qui affichera une TextView. Voici mon adaptateur:
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 est juste un FrameLayout avec un TextView à l'intérieur ("display_name"). C'est l'eror:
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)
Merci beaucoup!
Attendez que la vue soit créée avant la liaison.
Supprimez TextView userNameInList= v.findViewById(R.id.display_name);
de votre MyRvAdapter.ViewHolder
.
Et liez dans ViewHolder
comme mTextView = v.findViewById(r.id.display_name);
.
Dans mon cas, je l'ai corrigé en changeant cette ligne
val view = parent.inflate(R.layout.your_item)
à
val view = parent.inflate(R.layout.your_item, false)
essaye ça
public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.MyViewHolder> {
private Context mContext;
private String[] mDataset;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.display_name);
}
}
public MyRvAdapter(Context mContext, String[] myDataset) {
this.mContext = mContext;
this.mDataset = myDataset;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_row_item, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.title.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}