Android:如何使用ArrayAdapter获取微调器项的id

时间:2013-02-19 12:14:49

标签: android android-arrayadapter

我的微调器加载了一些消息,每条消息都有自己的id,

public class Message {
    private String id;
    private String message;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

     @Override
     public String toString() {          
         return  message;
     }
}

我将此message传递给Arrayadapter,

   protected List<Message> messages = null;
    ArrayAdapter <Message> arrayadapter = new ArrayAdapter<Message>( activity,android.R.layout.simple_spinner_item,messages);               
                        arrayadapter.setDropDownViewResource(R.layout.textview);
 spinner1.setAdapter(arrayadapter); 

现在我如何才能获得所选特定消息的ID? 我可以用arrayadapter做到这一点。感谢任何帮助

2 个答案:

答案 0 :(得分:8)

spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {
            Message mSelected = (Message) parent.getItemAtPosition(pos);
            Log.i("Id:", mSelected.getId());

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
            Log.i("Message", "Nothing is selected");

        }


    });

答案 1 :(得分:1)

你应该在spinner上设置项目点击监听器:

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Object item = parent.getItemAtPosition(pos);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
});