androidandroid-pageradapter

PagerAdapter - Wrong item index when clicked an item's button


I have a class that extends PagerAdapter. So I have overridden this function :

@Override
public Object instantiateItem(final ViewGroup container, final int position) {
    final View view;

        view = mLayoutInflater.inflate(R.layout.item, container, false);

        setFavButton(view, list.get(position));

    container.addView(view);
    return view;
}

private void setFavButton(View view, Word word) {
    btn_like = view.findViewById(R.id.btn_like);
    btn_like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            toggleFavButton(btn_like);
        }
    });
}


private void toggleFavButton(Button btn_like){
       btn_like.setCompoundDrawablesWithIntrinsicBounds(  R.drawable.ic_like_red, 0, 0, 0);
    }

So whenever I click a button on an item, it changes the drawable of another item's button. Same happens with all other buttons that I haven't mentioned. I click button to play audio, but it plays audio that is linked to some other item.


Solution

  • To avoid this problem, instead of creating a global Button variable in this adapter class, I created an instance of button inside instantiateItem()