Make two items in a Listview change position

Asked

Viewed 183 times

0

I’m creating a button called Up, to make an item in the listview go up, while the one above. But I’ve tried everything and it won’t, I don’t know if I’m wrong about logic.

But I’ve tried it in two ways. The first (Position is the ID of the item I clicked):

 auxtema = tema[posicao-1];
 auxpalavras = palavras[posicao-1];
 auxtempo = tempo[posicao-1];

 lista.remove(posicao-1);

 HashMap<String,String> substituir = new HashMap<String,String>();
 substituir.clear(); 
 substituir.put("tema",auxtema+": "+auxtempo);
 substituir.put("palavras",auxpalavras);
 lista.add(posicao,substituir);

((BaseAdapter) resumo.getAdapter()).notifyDataSetChanged(); 

The second form:

auxtema = tema[posicao];
auxpalavras = palavras[posicao];
auxtempo = tempo[posicao];

auxtema1 = tema[posicao-1];
auxpalavras1 = palavras[posicao-1];
auxtempo1 = tempo[posicao-1];

lista.remove(posicao-1);
lista.remove(posicao);

HashMap<String,String> substituir = new HashMap<String,String>(); 
substituir.put("tema",auxtema+": "+auxtempo);
substituir.put("palavras",auxpalavras); 
lista.add(posicao-1,substituir);

HashMap<String, String> substituir2 = new HashMap<String, String>();
substituir.put("tema",auxtema1+": "+auxtempo1);
substituir.put("palavras",auxpalavras1);
lista.add(posicao,substituir2);

I’m doing something wrong?

2 answers

2


Your code is a little confused and incomplete (I don’t see the list statement) but based on the description of your problem, I imagine you can do the following:

Collections.swap(lista, indice_posicao_item_cima, indice_posicao_item_baixo)

Comment if you still have any questions

  • It worked fine, thank you very much. I spent hours banging head and worked with a line, programming has these right. kkkk, thanks!

1

João Neto this does not work?

Object aux = lista.get(posicao-1);
lista.remove(posicao-1);
lista.add(posicao, aux);
  • It worked that way too! Thank you!

  • @Maiconcarraro You can also do this without changing the list size, using set(posição, objeto), nay?

  • @Piovezan if I give one set(posicao, aux) without the remove before it will overwrite the element I wanted to climb up and duplicate what was going down.

  • Only use aux also, no? Object aux = lista.get(posicao1); lista.set(posicao1, lista.get(posicao2); lista.set(posicao2, aux); In the source code of Collections.swap() is even more compact (it doesn’t seem like it works heheh): l.set(i, l.set(j, l.get(i)));

  • Oh yes, if I save the value and do two sets yeah.

Browser other questions tagged

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