【发布时间】:2020-01-17 19:59:11
【问题描述】:
我是 android 和 java 的新手。我无法在onBindViewHolder 函数中调用ViewHolder.setCategoryName(name);。我知道可能有类似的问题,但还没有对我有用。编译器给出错误“不能从静态上下文调用非静态函数”,我没有在我的代码中的任何地方使用静态关键字。
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);
}
}
}
【问题讨论】:
-
尝试
holder.setCategoryName(...)而不是ViewHolder.setCategoryName(name);BTW 类名后跟.后跟方法名被解释为调用Java 中的静态方法 -
尝试使用 public void setCategoryName(String name){ categoryName.setText(name); }
标签: java android android-recyclerview static non-static