Kristian
Kristian

Reputation: 202

Why is my recyclerView redoing stuff in onBindViewHolder?

I have a recyclerView and in this recyclerView I have an object which is displayed on my layout few times. I wanted to try to change the exact object on exact position like so:

@Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder0, int i) {

            //we reference our object on position i
            viewHolder0.file.setText(mObjects.get(i).getFile());
            //we do the same for sets
            viewHolder0.sets.setText(mObjects.get(i).getSets())
            Log.i("mLOG", "value of i = "+i);

            //now I want to change only the second object 
            if(i == 2){
                viewHolder0.max.setBackgroundResource(R.drawable.person_image);
                viewHolder0.max.setText("8");
            }
            

    }

It changes the object on the second position but it also changes every other on the 2 + 9 position (2, 11 , 20 ...) Even the value in the LOG's is i= 1,2,3,4,5,6...x it is never 2 again. Why is this happening? I would like to have a change only on the object on the second position.

This is my call from the activity

    private void insertFakeInfo(){

        for (int i = 0; i < 100; i++){
            MaxWindow mMax = new MaxWindow();

            mMax.setFile("Whatever" + i);
            mMax.setSets("" + i);

            mObjects.add(mMax);
        }
        mMaxAdapter.notifyDataSetChanged();
    }
Thanks for any advice in advance. :)

Upvotes: 0

Views: 43

Answers (1)

Sarah Khan
Sarah Khan

Reputation: 866

In your code, add the highlighted line

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder0, int i) 
{

    //we reference our object on position i
    viewHolder0.file.setText(mObjects.get(i).getFile());
    //we do the same for sets
    viewHolder0.sets.setText(mObjects.get(i).getSets())
    Log.i("mLOG", "value of i = "+i);

    //now I want to change only the second object 
    if(i == 2){
        viewHolder0.max.setBackgroundResource(R.drawable.person_image);
        viewHolder0.max.setText("8");
    }
    **else {
        viewHolder0.max.setBackgroundResource(R.drawable.some_other_image);
        viewHolder0.max.setText("some other string");
    }**
    

}

Upvotes: 1

Related Questions