java - 无法解析方法'get(java.lang.String)'
问题描述
如何在 recyclerView 中获取行位置并解决获取问题
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
private String[] listOfItems;
public MyListAdapter(String[] listOfItems){
this.listOfItems = listOfItems;
}
@Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int i) {
Boolean attachViewImmediatelyToParent = false;
View singleItemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent,attachViewImmediatelyToParent);
MyViewHolder myViewHolder = new MyViewHolder(singleItemLayout);
return myViewHolder;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.textShow.setText(listOfItems[position]);
holder.textShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Resolve the problem of get in Toast
Toast.makeText(holder.textShow.getContext(), "you pressed the " + listOfItems.get(holder.getLayoutPosition()+" item"), Toast.LENGTH_SHORT).show();
Resolve the problem of getting in Toast
}
});
}
@Override
public int getItemCount() {
return listOfItems.length;
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView textShow;
public MyViewHolder(View itemView) {
super(itemView);
textShow = (TextView) itemView.findViewById(R.id.tvphrase);
}
}
}
解决方案
小心,有两个问题:
Toast.makeText(holder.textShow.getContext(), "you pressed the " + listOfItems.get(holder.getLayoutPosition()+" item"), Toast.LENGTH_SHORT).show();
1)你有拼写错误:连接+ "item"
应该在右括号之后)
2)listOfItems
是数组,不是列表,所以使用应该使用[]
语法。
所以,正确的线是
Toast.makeText(holder.textShow.getContext(), "you pressed the " + listOfItems[holder.getAdapterPosition()]+" item", Toast.LENGTH_SHORT).show();
更新PS
同样,它更好地使用getAdapterPosition()
而不是getLayoutPosition()
在听众内部
推荐阅读
- python - Django-在一个模板中使用两个基于类的视图
- node.js - 使用一个 NPM 命令启动 react-create-app 和 Electron.js
- python-3.x - Python Windows 运行 Bash 命令
- python - 在请求有效负载中创建变量时需要帮助
- python - Python正则表达式除字母f之外的所有字母a-zA-Z?
- c++ - C++ 指向枚举数组的指针
- c++ - Bison/yacc 解析器在不被空格分隔时跳过语法 - “意外的 $end”
- php - MAC上的Outlook“.EML”文件目录?
- python - Pisarze - 来自波兰信息学奥林匹克竞赛的数据分析任务
- r - 对415个文件进行线性回归,只输出文件名、回归系数、显着性