How to create a Listview with Random items? (Android)

Asked

Viewed 158 times

0

I’m having trouble with my Listview. I would like him to display his items in an Random way, but not to repeat the items, as is happening now.

Here is the code:

public class AdapterConteudo  extends BaseAdapter{

private Context ctx;
private List<Cardapio> listaCardapio;

public AdapterConteudo(Context ctx, List<Cardapio> listaCardapio){
    this.ctx = ctx;
    this.listaCardapio = listaCardapio;
}

@Override
public int getCount(){
    return listaCardapio.size();
}

@Override
public Object getItem(int posicao){
    return listaCardapio.get(posicao);
}

@Override
public long getItemId(int posicao){
    return listaCardapio.get(posicao).getId();
}

@Override
public View getView(int posicao, View convertView, ViewGroup parent){
    Cardapio cardapio = listaCardapio.get(new Random().nextInt(listaCardapio.get(posicao).getId()));

    View view = LayoutInflater.from(ctx).inflate(R.layout.fragment_lista, null);
    TextView item = (TextView) view.findViewById(R.id.textViewItem);
    TextView conteudo = (TextView) view.findViewById(R.id.textViewConteudo);
    TextView telefone = (TextView) view.findViewById(R.id.textViewTelefone);

    item.setText(cardapio.getItem());
    conteudo.setText(cardapio.getConteudo());
    telefone.setText(cardapio.getTelefone());

    return view;
}

}

In the Fragment where the listview is:

private void preencheLista(){

        listaCardapio = new ArrayList<Cardapio>();

        Cardapio cardapio1 = new Cardapio(1, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio1);

        Cardapio cardapio2 = new Cardapio(2, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio2);

        Cardapio cardapio3 = new Cardapio(3, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio3);

        Cardapio cardapio4 = new Cardapio(4, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio4);

        Cardapio cardapio5 = new Cardapio(5, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio5);

        Cardapio cardapio6 = new Cardapio(6, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio6);

        Cardapio cardapio7 = new Cardapio(7, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio7);

        Cardapio cardapio8 = new Cardapio(8, "Item", "Conteúdo",
                "telefone");
        listaCardapio.add(cardapio8);

    }

1 answer

0


Instead of trying to do it on Adapter do it directly on the Arraylist.

After filling the list use the method shuffle class Collections.

Collections.shuffle(listaCardapio);

The items of listaCardapio evening "shuffled" randomly.

  • Thank you so much! It worked. It was exactly what I was looking for. Thanks!

Browser other questions tagged

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