Change layout using a spinner in Android

╄→гoц情女王★ 提交于 2019-12-25 08:16:17

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/22294576/change-layout-using-a-spinner-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!