List changes color in wrong position

1

ImadeamethodforwhenIclickonalistViewitemitwillchangecolor.
Theproblemisthatitalsochangescolorallitemsthathavearangeof12itemitemsthatIclicked.
Forexample:
IhavealistViewwithnumbersfrom1to30,ifIclickthenumber1itwillturngreen,butthe13also25willalsogogreen.
IsawthatthisisalistViewproblembutsomeonehashadasimilarproblemandknowshowtosolveit?

CodeIamusing:

@OverridepublicvoidonItemClick(AdapterView<?>parent,Viewview,intposition,longid){StringstringNomeProduto=adapter.getItem(position);Intenti=newIntent(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);

}
    
asked by anonymous 13.08.2015 / 15:21

2 answers

1

The image explains perfectly why this is happening.

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

You have to ensure that it has the color "not clicked" before it can be reused.

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

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

In your adpater , in the getView() method, you should put the respective color in case the row has been clicked.

    
13.08.2015 / 16:19
1

The correct one would be to handle the change not on the onItemClick. You should create a view that stores the click state and uses it as the basis for the adapter.

I can not post code here because I am answering from the cell, but the link has an example that works very well using a checkbox to keep the state of selection.

In your case, you can treat inside the adapter to change the color when the state of the checkbox changes.

Edited, the link was in error. LINK FIXED

    
14.08.2015 / 01:32