Can I use two list of string for one spinner?
I want to use a spinner which can handle two String a开发者_运维问答rraylist simultaneously. What exactly I want is when users click on spinner so appearing view should show String items of 1st arraylist but after selecting one of the item so on that spinner it should show corresponding item of 2nd arraylist.
For eg I have 2 list 1st is state list & 2nd is state code list so when I press spinner so appearing view should show list of state but after selecting one of the state(say Albama) spinner should show state code(AL).
The cleanest way to do it would be to wrap the data properly in an object. The toString method will be used to tell how to display the data in the spinner. Then in your OnClick listener, you can get the State from the adapter and then its code.
public class State {
String code;
String name;
public State(String n, String c) {
name = n;
code = c;
}
public String toString() {
return name;
}
}
Then use an array list of State objects for your adapter.
Example based on the Hello, Spinner tutorial:
Replace:
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.planets, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
By:
State[] states = new State[] { new State('Alabama', 'AL'), new State('California', 'CA') };
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, states);
In the onClick()
method of first spinner create another spinner at runTime and attach the second string array to it based on the item clicked.. i mean something like this..
Spinner s1 = findViewById(R.id.spinner01);
ArrayAdapter a = new ArrayAdapter(/*/required stuff*/,array1)
s1.setAdapter(a);
s1.setOnClickListener(new OnClickListener(){
protected void onClick(View v){
Spinner s = new Spinner(/*/activity Instance*/);
ArrayAdapter a1 = new ArrayAdapter(/*/required stuff*/,array2)
s.setAdapter(a1);
//rest goes here
}
});
精彩评论