List changes color at wrong position

Asked

Viewed 101 times

1

Estou com o problema desta imagem:I made a method for when I click on a listview item it change color.
The problem is that it also changes color all items that have a range of 12 items of the item I clicked.
For example:
I have a listview with numbers from 1 to 30, if I click on the number 1 it will turn green, however the 13 also 25 will also.
I saw that this is a listview problem but someone has had some similar problem and knows how to solve?

Code I’m using:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {

    String stringNomeProduto = adapter.getItem(position);
    Intent i = new Intent(this, Formulario.class);
    i.putExtra("stringNomePais", stringNomePais);
    i.putExtra("stringIdContinente", getIdContinente);
    startActivityForResult(i, 0);

    //muda de cor o produto que já foi preenchido

    System.out.println("resultado 2: " + resultado);
    if (adapter.getItem(position).equals(resultado)) {
        View v = adapter.getView(position, view, parent);
        v.setBackgroundColor(Color.LTGRAY);
    }
    adapter.getItem(position);

}
  • Where is the color change being made? Post this code.

  • my code is as simple as possible, I think it won’t help at all, posted an image showing how listview works, is this problem I’m having.

1 answer

1

The picture perfectly explains why this is happening.

Suppose item 1 is the one where you change the color, as it is reused, when generating item 8, it also appears with the color changed.

You have to make sure it has the color "not clicked" before it can be reused.

The space between lines where this happens depends on the number of lines that can be displayed at the same time.
In the case of the image example there are seven, in your case there are 12.

When a line is no longer visible, its View can be reused to be used in another line.

In his adpater, in the method getView(), should set the respective color in case the line has been clicked or not.

  • That’s exactly it Ramaral, but on what I’m picking up, you know how I can ensure that it has the color of "not clicked"? I thank you in advance.

  • Without seeing your code no.

  • posted the code.

  • I edited the answer.

  • thanks, but I’ve tried this before, it doesn’t work.

  • This will have to be done in the Adapter in the method getView()

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.