开发者

Populating a dependent spinner from an independent spinner

I have a Spinner object that contains an array of strings populated with the 50 states i开发者_C百科n the United States.

I also have some more arrays that contain lists of cities for the different states. What I am wanting to do is to populate the dependent spinner with the array of cities from the state that was selected by the other spinner.

For exampe:

First spinner selected - Alaska

Second spinner - Anchorage, Fairbanks, Ketchikan, Kodiak.

Another example:

First spinner selected - Florida

Second spinner - Key West, Tallahassee.

The problem is that I'm not sure how to populate the dependent spinner based on the state spinner selected.

The Array Adapter that I am using accepts an integer value that references the array that is used to populate the spinner.


I don't know the exact API calls you're using, but here's the general approach I'd use:

class CitySpinnerFactory {

    Map<String,Spinner> stateToCitySpinner = new HashMap<String,Spinner>();

    public void map(String state, Spinner citiesForState) {
        stateToCitySpinner.put(state,citiesForState);
    }

    public Spinner spinnerForState(String state) {
        return stateToCitySpinner.get(state);
    }

}

And later you might do this to populate the cities and states

Spinner states = new Spinner();
Spinner cities = null;
CitySpinnerFactory cityFactory = new CitySpinnerFactory();

states.add("Alabama");
cities = new Spinner();
cities.add("Birmingham"); // city in AL
cities.add("Mobile"); // city in AL
cityFactory.map("Alabama",cities);

states.add("Alaska");
cities = new Spinner();
cities.add("Juneau"); // city in AK
cities.add("Anchorage");
cityFactory.map("Alaska",cities);
// ... add other states

And later you might do this to get the cities out

String state = states.spin(); // making up method to get a random state...
Spinner cities = cityFactory.spinnerForState(state);
String city = cities.spin();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜