多个Spinner同时监听,判断是哪个Spinner做了回调

首先有3个spinner控件,分别是性别、民族、学历 

为其添加适配器和数据源

//性别spinner和适配器
String[] sex = getResources().getStringArray(R.array.sexs);
ArrayAdapter adapterSex = new ArrayAdapter(this,android.R.layout.simple_spinner_item,sex);
spActivityModifyPersonalSex.setAdapter(adapterSex);
spActivityModifyPersonalSex.setOnItemSelectedListener(this);
//民族spinner和适配器
String[] nation = getResources().getStringArray(R.array.nations);
ArrayAdapter adapterNation = new ArrayAdapter(this,android.R.layout.simple_spinner_item,nation);
spActivityModifyPersonalNation.setAdapter(adapterNation);
spActivityModifyPersonalNation.setOnItemSelectedListener(this);
//学历spinner和适配器
String[] educations = getResources().getStringArray(R.array.educations);
ArrayAdapter adapterEducation = new ArrayAdapter(this,android.R.layout.simple_spinner_item,educations);
spActivityModifyPersonalEducations.setAdapter(adapterEducation);
spActivityModifyPersonalEducations.setOnItemSelectedListener(this);


接口回调中根据parent.getID();来判断是哪个Spinner控件的接口回调


@Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {

    Logger.t("activityModifyPersonal").d("id   "+id);
    Logger.t("activityModifyPersonal").d("view.getId()   "+view.getId());
    Logger.t("activityModifyPersonal").d("parent.getId()   "+parent.getId());
    Logger.t("activityModifyPersonal").d("R.id.sp_activity_modify_personal_sex  "+R.id.sp_activity_modify_personal_sex);
    Logger.t("activityModifyPersonal").d("R.id.sp_activity_modify_personal_Nation   "+R.id.sp_activity_modify_personal_Nation);
    Logger.t("activityModifyPersonal").d("R.id.sp_activity_modify_personal_educations   "+R.id.sp_activity_modify_personal_educations);

    switch (parent.getId()){
        case R.id.sp_activity_modify_personal_sex:
            //性别
            sex = (String) parent.getSelectedItem();
            Logger.t("activityModifyPersonal").d("select性别"+sex);
            break;
        case R.id.sp_activity_modify_personal_Nation:
            //民族
            nation = (String) parent.getSelectedItem();
            Logger.t("activityModifyPersonal").d("select民族"+nation);
            break;
        case R.id.sp_activity_modify_personal_educations:
            //教育
            education = (String) parent.getSelectedItem();
            Logger.t("activityModifyPersonal").d("select教育"+education);
            break;
    }
}

@Override
public void onNothingSelected(AdapterView parent) {

}

你可能感兴趣的:(【android】技术分享)