Android-CleanArchitecture
Android-CleanArchitecture copied to clipboard
UnsupportedOperationException due to injection of Application Context while inflating layout in adapter.
So I was trying to set android:background="?selectableItemBackground" on the adapter item view when I ran into this issue. On further research I found out that passing application context while creating custom view results in this issue. This seriously limits injecting the adapter.
Thanks
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private List<MyItem> items;
public MyAdapter(Context context, List<MyItem> items) {
this.context = context; // Ensure you pass Activity Context here
this.items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Inflate view using the Activity context
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Bind data to the view holder
MyItem item = items.get(position);
holder.textView.setText(item.getText());
// Example of setting background
holder.itemView.setBackgroundResource(R.attr.selectableItemBackground);
}
@Override
public int getItemCount() {
return items.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
}
}
}