How to create a ListView with random items? (Android)

0

I'm having problems in my ListView. I would like it to display its items randomly, but the items do not repeat themselves, 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);

    }
    
asked by anonymous 13.05.2015 / 03:09

1 answer

0

Instead of trying to do this in the Adapter do it directly on the ArrayList .

After populating the list use the shuffle of the Collections class.

Collections.shuffle(listaCardapio);

Items of listaCardapio will randomly shuffle .

    
13.05.2015 / 11:33