开发者

onItemSelected property of spinner in android

Spinner spin1 = (Spinner) findViewById(R.id.spinner1);
spin1.setOnItemSelectedListener(this);
spin2 = (Spinner) findViewById(R.id.spinner2);
spin2.setOnItemSelectedListener(this);
ArrayAdapter<String> choice1 = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, data1);
    choice1
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    choice2 = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, data2);
    choice2
       开发者_开发知识库     .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

In this code i am creating two drop downs and now my requirement is when i select the item from first combo the data in the second combo must be changed according to the selected item of first combo.

now in onItemSelected property how to code specially for first dropdown?


public void onItemSelected(AdapterView parent, View v,int position, long id) {
 // you decide here based on parent

if (parent==spin1) {
// do something with spin1
}
else if (parent==spin2) {
// do something with spin2
}
}


Your class (this) is a listener for events that are fired, when the selection of one of two spinners changes.

So the class has to implement the interface method which catches those events. Inside this method, you (1) determine which spinner fired the event (= has changed) and, if it is spinner 1, (2) get the actual value from spinner 1 and (3) use the value to set spinner 2. This might result in another event which has to be ignored.

EDIT

one of the interface methods of AdapterView.OnItemSelectedListeneris

public abstract void  onItemSelected  (AdapterView<?> parent, View view, int position, long id);

The AdapterView (parent) which is passed is exactly that object that fired the event, so either parent == spin1 or parent == spin2 is true (unless you don't listen to more widgets).

BTW: spin1 and spin2 need to be class members because the onItemSelect methods needs to access them.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜