开发者

Dynamic Spinners in Android (General Workflow Question)

Like this one, I've seen a few how-to's on this site, but truthfully, I'm not really getting it.

I want one spinner's content to be based upon a previous spinner selection, like in a States and Cities scenario. In general terms, what is the workflow? Are the results of the second spinner filtered based on the first spinner, or is the second spinner pointing to a completely different list based on the first spinner?

For my own simple learning project, I've built several string-arrays in the strings.xml (AL-Cities, AK-Cities, AR-Cities, etc). I'd like the city spinner to populate from the correct array based on a choice from the state spinner. But I'm wondering if instead I should just have one large multidimensional array of "Cities" that have a state abbreviation as an additional identifier, and then point the second spinner at that using the state abbreviation as a filter. It would seem like the former would provide better performance.

Any help (and code examples) would be greatly appreciated. I'm not new to programming (php mostly, so I guess scripting is more accurate), but I am new to java. My code so far 开发者_如何学Gowith the spinners not linked is below with the second spinner pointing to an undifferentiated city_array.

Thank you!

public class Example1 extends Activity {

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.example1);

   Spinner spinState = (Spinner) findViewById(R.id.spin_state);
    ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(
            this, R.array.state_array, android.R.layout.simple_spinner_item);
    adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinState.setAdapter(adapter3);

    Spinner spinCity = (Spinner) findViewById(R.id.spin_city);
    ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(
            this, R.array.city_array, android.R.layout.simple_spinner_item);
    adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinCity.setAdapter(adapter4);
}
}


You could try and get the position from your first spinner, the one you've selected and then populate your second spinner after retrieving the proper array based on that position.

You have to listen for your first adapter being changed:

    spinner. setOnItemSelectedListener(new MyOnItemSelectedListener());


class MyOnItemSelectedListener implements OnItemSelectedListener {
    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
        String choice = parent.getItemAtPosition(pos).toString();
            populateSecondSpinnerMethod(choice)
       }
    }
    public void onNothingSelected(AdapterView parent) {       // Do nothing.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜