我有一个实现RecyclerView.Adapter的类,并且在onBindViewHolder中调用onClick监听器来访问另一个Fragment。我有这个错误,并指回上下文。代码snipet如下:
$printClass = [wmiclass]'win32_printer'
$printClass.AddPrinterConnection($printer)
我已经在全球范围内实施了我的上下文,并且被告知这不是一个好习惯。 下面是我需要访问的完整类和Fragment类。
((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
要访问的片段类
public class Topdeal_CustomAdapter extends RecyclerView.Adapter<Topdeal_CustomAdapter.ViewHolder> {
public static final String CATEGORY_NAME = "name";
public static final String CATEGORY_IMAGE = "image";
public static final String the_Id = "000000000";
private List<Categories_ItemObject> categories_List;
private Context context;
public Topdeal_CustomAdapter(List<Categories_ItemObject> developersLists, Context context) {
this.categories_List = developersLists;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_topdeal, parent, false);
return new Topdeal_CustomAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Categories_ItemObject developersList = categories_List.get(position);
holder.name.setText(developersList.getCategoryName());
Picasso.with(context).load(developersList.getCategoryPicture()).into(holder.picture);
holder.picture.setOnClickListener(new View.OnClickListener(context) {
@Override
public void onClick(View v) {
TopDeal_two fragment = new TopDeal_two();
Bundle bundle = new Bundle();
bundle.putString(CATEGORY_NAME, developersList.getCategoryName());
fragment.setArguments(bundle);
((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
});
}
@Override
public int getItemCount() {
return categories_List.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView picture;
TextView name;
LinearLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
picture = itemView.findViewById(R.id.category_image);
name = itemView.findViewById(R.id.category_name);
relativeLayout = itemView.findViewById(R.id.linearLayout_category);
}
}
}
mAJOR问题在FragmentActivity上...... getSupportFragmentManager ....
答案 0 :(得分:0)
应用程序上下文不能转换为其他类型的上下文。
看起来您正在使用应用程序上下文创建Topdeal_CustomAdapter
,但随后在适配器内部将其转换为FragmentActivity。
最好在创建适配器时使用活动上下文('this'),因为适配器与您的活动生命周期相关联。