Can my spinner's entries depend on another spi

2019-08-05 15:25发布

问题:

I have had no formal training in programming at all yet (I'm a freshman in college, though, and going to major in it), and am trying to learn Android after only knowing Visual Basic, so I need a lot of help. Here's the code I have so far:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.Books, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter1);
    spinner1.setOnItemSelectedListener(
            new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    // Here's what I need help with. I basically want it to say:
                     switch(position) {

                     case 0:
                         // Here I want it to set spinner2's entries to R.array.Five
                     case 1:
                         //Here I want to set spinner2's entries to R.array.Three
                    //etc...
                }
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

    Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.Five, android.R.layout.simple_spinner_item);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner2.setAdapter(adapter2);
    spinner2.setOnItemSelectedListener(
            new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    //(something similar)
                }
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
}

Is it possible to change the entries array of one spinner from another spinner's onItemSelected method? What code do I need to add where? Trying to say something about spinner2 or adapter2 in spinner1's OnItemSelectedListener says it's a misplaced construct. Which makes sense, but I don't know how to get around that.

回答1:

Just define the alternative ArrayAdapter(s) at top of OnCreate method with alternate sets defined. Further, move up the definition of spinner2 above the definition of OnItemSelectedListener so it can be accessible inside the inner class. The spinner variable as well as the array adapters must be finalized to be accessible inside the inner class.

Change the adapter by simply invoking spinner2.setAdapter(....) inside the swith-case statement.

This will work as long as you only want to handle static sets of elements in your spinner.