如何在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);
}
}
}
答案 0 :(得分:1)
ListofItem
是Java中的Array
而非List
。
您应该使用:
listOfItems[holder.getLayoutPosition()];
您应该检查要在``尝试访问的项目的索引是否没有超出范围:
if (holder.getLayoutPosition() < listOfItems.length) {
listOfItems[holder.getLayoutPosition()];
}
else {
Log.d("TAG", "Error: index out of bounds");
}
要访问Java成员:
最佳
答案 1 :(得分:1)
请注意,有两个问题:
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();
更新 P.S。
同样,最好在监听器中使用getAdapterPosition()
而不是getLayoutPosition()