Метод getAdapterPosition () RecycleView.V всегда returen -1

При использовании RecycleView getAdapterPosition()всегда возвращается -1.Не знаю почему.

Мои onCreateViewHolderкоды следующие :

public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
    final ViewHolder holder = new ViewHolder(view);
    // add OnClickListener
    holder.mFruitView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = holder.getAdapterPosition();
            Fruit fruit = mFruitList.get(position);
            Toast.makeText(v.getContext(),"You Click : " + fruit.getName(),Toast.LENGTH_SHORT).show();
        }
    });
    return new ViewHolder(view);
}

И мой ViewHolder коды, как это :

static class ViewHolder extends RecyclerView.ViewHolder{
    View mFruitView;
    ImageView fruitImage;
    TextView fruitName;
    public ViewHolder(View itemView) {
        super(itemView);
        mFruitView = itemView;
        fruitImage = (ImageView) itemView.findViewById(R.id.iv_fruit);
        fruitName = (TextView) itemView.findViewById(R.id.tv_fruit);
    }
}

Журналы при возникновении ошибки следующие :

java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1

Любая помощь будет благодарна

3 ответа

  1. Мои Коды Адаптера :

    public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
    
    private static final String TAG = "FruitAdapter";
    private List<Fruit> mFruitList;
    public FruitAdapter(List<Fruit> fruitList){
        mFruitList = fruitList;
    }
    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        final ViewHolder holder = new ViewHolder(view);
        // add OnClickListener
        holder.mFruitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"You Click : " + fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        });
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }
    
    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
    
    static class ViewHolder extends RecyclerView.ViewHolder{
        View mFruitView;
        ImageView fruitImage;
        TextView fruitName;
        public ViewHolder(View itemView) {
            super(itemView);
            mFruitView = itemView;
            fruitImage = (ImageView) itemView.findViewById(R.id.iv_fruit);
            fruitName = (TextView) itemView.findViewById(R.id.tv_fruit);
        }
    }
    }
    
  2. Изменение адаптера:

    public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
    
        private static final String TAG = FruitAdapter.class.getSimpleName();
        private List<Fruit> mFruitList;
    
        public FruitAdapter(List<Fruit> fruitList) {
            mFruitList = fruitList;
        }
    
        @Override
        public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
            return new ViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            final Fruit fruit = mFruitList.get(position);
            holder.fruitImage.setImageResource(fruit.getImageId());
            holder.fruitName.setText(fruit.getName());
            holder.mFruitView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(), "You Click : " + fruit.getName(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    
        @Override
        public int getItemCount() {
            if (mFruitList == null) return 0;
            else return mFruitList.size();
        }
    
        static class ViewHolder extends RecyclerView.ViewHolder {
            View mFruitView;
            ImageView fruitImage;
            TextView fruitName;
    
            public ViewHolder(View itemView) {
                super(itemView);
                mFruitView = itemView;
                fruitImage = (ImageView) itemView.findViewById(R.id.iv_fruit);
                fruitName = (TextView) itemView.findViewById(R.id.tv_fruit);
            }
        }
    }
    
  3. Метод getAdapterPosition()всегда возвращает -1при recyclerviewвыполнении расчетов компоновки.
    Вы вызываете эти методы внутри ViewHolder. Это значит RecyclerViewделает расчеты.
    Если вам нужна позиция внутри действий click представления, вызовите его в onClick(final View v)методе public void, например:

    public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
    
        private static final String TAG = "FruitAdapter";
    
    private List<Fruit> mFruitList;
    
    public FruitAdapter(List<Fruit> fruitList) {
        mFruitList = fruitList;
    }
    
    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
    
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
    
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(), "You Click : " + fruit.getName(), Toast.LENGTH_SHORT).show();
            }
    
            @Override
            public int getItemCount() {
                return mFruitList.size();
            }
    
            static class ViewHolder extends RecyclerView.ViewHolder {
                View mFruitView;
                ImageView fruitImage;
                TextView fruitName;
    
                public ViewHolder(View itemView) {
                    super(itemView);
                    mFruitView = itemView;
                    fruitImage = (ImageView) itemView.findViewById(R.id.iv_fruit);
                    fruitName = (TextView) itemView.findViewById(R.id.tv_fruit);
                }
            }
        }