Use of Spinner on Android

Asked

Viewed 385 times

1

I am developing an application Android, and in it I have a Spinner and from the choice that the user makes in this Spinner it goes to certain page.

I had done so:

//Acionando_Items_no_Spinner
public void addListenerOnSpinnerItemSelection() 
{
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
public void addListenerOnButton() 
{
    spinner1 = (Spinner) findViewById(R.id.spinner1);//Informação_Do_Spinner
    button = (Button) findViewById(R.id.button);//Informação_Do_Botão
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //Escolha_da_pagina
            if(String.valueOf("São Paulo") != null){  
                setContentView(R.layout.activity_page2);
            }else{
                if(String.valueOf("Rio de Janeiro") != null){  
                    setContentView(R.layout.activity_page3);
                }
            }

        }
    });
}

At first it worked, but when you have more than one option, as shown in the code above, it enters the first if and even if he’s wrong he gives the result of the first if.

1 answer

3


The fact that he always goes into the first if is that String.valueOf is always different from null.

I believe what you want to do is if in relation to the item of Spinner and for that you need to make the following amendment:

public void addListenerOnButton() {
    spinner1 = (Spinner) findViewById(R.id.spinner1);//Informação_Do_Spinner
    button = (Button) findViewById(R.id.button);//Informação_Do_Botão

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String valorDoSpinner = spinner1..getSelectedItem().toString();
            //Escolha_da_pagina
            if(valorDoSpinner.equals("São Paulo")){  
                setContentView(R.layout.activity_page2);
            }else if(valorDoSpinner.equals("Rio de Janeiro")){  
                setContentView(R.layout.activity_page3);
            }
        }
    });
}

In addition there is another problem not mentioned, it is not possible to call setContentView after having already called on onCreate. You’ll need to start another Activity using Intent or go for the use of Fragments.

  • 1

    Thank you very much, you simplified it well, I was seeing more difficult ways. Thank you

Browser other questions tagged

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