[英]Android Recycler View problem in "onBindViewHolder" function "static method cannot be called from non-static method"
我是 android 和 java 的新手。 我无法调用ViewHolder.setCategoryName(name);
在onBindViewHolder
函数中。 我知道可能有类似的问题,但还没有对我有用。 编译器给出错误“不能从静态上下文调用非静态函数”,我没有在代码中的任何地方使用 static 关键字。
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
private List<CategoryModel> categoryModelList;
public CategoryAdapter(List<CategoryModel> categoryModelList) {
this.categoryModelList = categoryModelList;
}
@NonNull
@Override
public CategoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_item,viewGroup,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CategoryAdapter.ViewHolder holder, int position) {
String icon = categoryModelList.get(position).getCategoryIconLink();
String name = categoryModelList.get(position).getCategoryName();
ViewHolder.setCategoryName(name);
}
@Override
public int getItemCount() {
return categoryModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView categoryIcon;
private TextView categoryName;
public ViewHolder(@NonNull View itemView) {
super(itemView);
categoryIcon = itemView.findViewById(R.id.category_icon);
categoryName = itemView.findViewById(R.id.category_name);
}
private void setCategoryIcon(){
}
private void setCategoryName(String name){
categoryName.setText(name);
}
}
}
问题是您的方法不是静态的,但您试图从静态上下文调用:
private void setCategoryName
您需要执行以下操作:
private static void setCategoryName
但是,对于这种类型的操作,您可以只使用 holder 变量:
holder.bind(categoryModelList.get(position))
尝试这个:
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
private List<CategoryModel> categoryModelList;
public CategoryAdapter(List<CategoryModel> categoryModelList) {
this.categoryModelList = categoryModelList;
}
@NonNull
@Override
public CategoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_item,viewGroup,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CategoryAdapter.ViewHolder holder, int position) {
holder.bind(categoryModelList.get(position))
}
@Override
public int getItemCount() {
return categoryModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView categoryIcon;
private TextView categoryName;
public ViewHolder(@NonNull View itemView) {
super(itemView);
categoryIcon = itemView.findViewById(R.id.category_icon);
categoryName = itemView.findViewById(R.id.category_name);
}
public void bind(CategoryModel categoryModel){
categoryName.setText(categoryModel.getCategoryName());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.