[英]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.