Question

I'm trying to change the layout of my activity according to my selection inside the spinner. But after the first selection, the spinner become white and I'm not able to decide another selection. The code I'm using is the following:

public class MainActivity extends Activity implements OnItemSelectedListener {

Spinner spinner;
String[] options = { "Modulo1", "Modulo2" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, options);
    adapter_state
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter_state);
    spinner.setOnItemSelectedListener(this);

}

int check = 0;

public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    check = check + 1;
    if (check > 1) {
        int selState = spinner.getSelectedItemPosition();
        switch (selState) {
        case 0:
            setContentView(R.layout.activity_main);

            break;
        case 1:
            setContentView(R.layout.activity2_main);

            break;

        }

    }
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

//
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

Any suggestion? Thanks

Was it helpful?

Solution

The spinner you are referring to is in your first activity. After you have replaced the content, the spinner isn't there anymore. If you have another spinner in the second layout, you have to reconnect it and set the listener again. Basically you have to run your onCreate stuff after every setContentView...

As a side note, whatever you are trying to do, this is probably not the way to go. To show another full layout, better use another activity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top