Android微调器,获取selectedItem

时间:2016-03-15 19:21:05

标签: java android spinner onitemselectedlistener

正如我曾经指导过的那样,我正在开发一个“预约预约”应用程序。在其中,它有一个微调器,用户可以在其中选择该位置。 在BookAppointment.java中,这是微调代码:

public void addListenerOnSpinnerItemSelection() {
    pspinner = (Spinner) findViewById(R.id.spinner1);
    pspinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}

CustomOnItemSelectedListener.java

public class CustomOnItemSelectedListener implements OnItemSelectedListener {
BookAppointment ba = new BookAppointment();
String place;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
    Toast.makeText(parent.getContext(),
            "OnItemSelectedListener: " + parent.getItemAtPosition(pos).toString(),
            Toast.LENGTH_SHORT).show();
    place = parent.getItemAtPosition(pos).toString(); //the actual selected item of spinner
    ba.setPlace(place);
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
}
}

BookAppointment.java我希望到达所选项目,所以我尝试了

public void setPlace(String place){
    this.place = place;
}

submit.onClick中有一个BookApp(user, place, completeDate); 在调试模式下,为什么onClick place将为null。但即使我更改spinnersetPlace也会运行,this.place将等于原place,但之后place等于null }。在BookAppointment.java中有一个全局public String place;,而我在BookAppointment.java中没有其他地方使用。请帮助我,我错过了什么?我做错了什么?

onClick:

public void addListenerOnButton() {
    btnSubmitP = (Button) findViewById(R.id.btnSubmitP);
    pspinner = (Spinner) findViewById(R.id.spinner1);
    btnSubmitP.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*May I should place here the spinner's findViewById ?*/
            place = pspinner.getSelectedItem().toString(); //to get the actual selected place
            String completeDate = date + " " + itemValue;
            Toast.makeText(BookAppointment.this,
                    "OnClickListener : " +
                            "\nHelyszín: " + place + //it prints the actual selected item
                            "\nDátum: " + completeDate,
                    Toast.LENGTH_SHORT).show();


            User user = userLocalStore.getLoggedInUser();
            if (user == null) {
                Toast.makeText(BookAppointment.this,
                        "user = null",
                        Toast.LENGTH_SHORT).show();
            }
            BookApp(user, place, completeDate); //Here the debug not display the place, nothin like place=null, nothing, only the user and completeDate's value
        }

    });
}

1 个答案:

答案 0 :(得分:0)

尝试在submit.onClick中添加:

String places= spinnerReferenceName.getSelectedItem().toString();

这应该从spinner返回所选的字符串。