Create a Spinner from a fixed list with more than 1 field

1

How do I add values to this Spinner?

I need to create a Spinner that contains 2 "fields" (cod, option).

Default values will be added, but the codes can not be changed later, so I need the cod field when adding other values, I will not have any problems.

For this purpose a ArrayList using a specific class:

public class ArrayPadrao {

    private int id;
    private int cod;
    private String opcao;

    public ArrayPadrao(int cod, String opcao) {

        this.id = cod;
        this.opcao = opcao;
    }

    public int getCod() {
        return cod;
    }

    public String opcao() {
        return opcao;
    }

    //O que este método retornar é o que Spinner mostrará.
    @Override
    public String toString() {
        return opcao;
    }
}

I tried in some ways but to no avail:

ArrayList<ArrayPadrao> lista = new ArrayList<>();
        lista.add(1, "aaa");

I saw some different options ( link ) with List<> and Map + HashMap but would like opinions on how best to do so.

  

Working Code:

public void spinnerTipo() {

        ArrayList<ArrayPadrao> lista = new ArrayList<>();
        lista.add(new ArrayPadrao(1, "aaa"));
        lista.add(new ArrayPadrao(2, "bbb"));
        lista.add(new ArrayPadrao(3, "ccc"));

        ArrayList<ArrayPadrao> tipos = lista;
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, tipos);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnTipo.setAdapter(adapter);
    }
    
asked by anonymous 25.01.2018 / 19:38

1 answer

1

You must first create an instance of ArrayPadrao and add it to the ArrayList like this:

ArrayList<ArrayPadrao> lista = new ArrayList<>();
lista.add(new ArrayPadrao(1, "aaa"));
    
25.01.2018 / 19:44