Is there a way to create a spinner just like the html selectbox, which has a text and a value?

0

As I said in the question, I need the data from my spinner to have a value and text, just as it happens to be the selectbox in html. It is important to have a key value so that the user sees a readable text and I can send a number (which is the value) to the server. I've been looking but I can not find anything. Any ideas?

    
asked by kosode 12.11.2018 в 09:54
source

1 answer

-1

Have you worked with classes? What you want to achieve could be solved in the following way.

  • Create a class with which you have a key and a value.
  • Then create a list of this class, then pass the list to your adapter for the Spinner.
  • Then get the selected object in the Spinner.
  • Extract the key, and send it to the database.
  • I leave this as a guide:

    public class MyItem {
        private String clave;
        private String valor;
    
        public MyItem(String clave, String valor) {
            this.clave = clave;
            this.valor = valor;
        }
    
        public String getClave() {
            return clave;
        }
    
        public void setClave(String clave) {
            this.clave = clave;
        }
    
        public String getValor() {
            return valor;
        }
    
        public void setValor(String valor) {
            this.valor = valor;
        }
    
        @Override
        public String toString() {
            return this.valor;
        }
    }
    

    Then create the items:

       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       //Crear datos de prueba
        ArrayList<MyItem> items = new ArrayList<>();
        items.add(new MyItem("clave1", "Valor1"));
        items.add(new MyItem("clave2", "Valor2"));
    
        //Crear el adaptador para el spinner
        ArrayAdapter<MyItem> adapter = new ArrayAdapter<MyItem>(this, android.R.layout.simple_expandable_list_item_1, items);
        spinner.setAdapter(adapter);
      }
    

    In the end you just need to get the spinner object and then do the respective get:

        MyItem myItem = (MyItem)spinner.getSelectedItem();
        String miClaveParaBD =  myItem.getClave();
    
        
    answered by 12.11.2018 в 20:39