首页 > 解决方案 > 无法解析方法'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);
        }
    }




}

在此处输入图像描述

标签: javaandroid

解决方案


小心,有两个问题:

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()在听众内部


推荐阅读