Thay vì phương pháp mảng kép, lý do tại sao không điền vào ArrayAdapter của bạn lập trình với các đối tượng của một kiểu đã biết và sử dụng nó. Tôi đã viết một hướng dẫn về bản chất tương tự (liên kết ở phía dưới) thực hiện điều này. Tiền đề cơ bản là tạo một mảng các đối tượng Java, báo cho trình quay số về và sau đó sử dụng các đối tượng đó trực tiếp từ lớp spinner. Trong ví dụ của tôi, tôi có một đối tượng đại diện cho một "Nhà nước" được quy định như sau:
package com.katr.spinnerdemo;
public class State {
// Okay, full acknowledgment that public members are not a good idea, however
// this is a Spinner demo not an exercise in java best practices.
public int id = 0;
public String name = "";
public String abbrev = "";
// A simple constructor for populating our member variables for this tutorial.
public State(int _id, String _name, String _abbrev)
{
id = _id;
name = _name;
abbrev = _abbrev;
}
// The toString method is extremely important to making this class work with a Spinner
// (or ListView) object because this is the method called when it is trying to represent
// this object within the control. If you do not have a toString() method, you WILL
// get an exception.
public String toString()
{
return(name + " (" + abbrev + ")");
}
}
Sau đó, bạn có thể cư một spinner với một mảng của các lớp này như sau:
// Step 1: Locate our spinner control and save it to the class for convenience
// You could get it every time, I'm just being lazy... :-)
spinner = (Spinner)this.findViewById(R.id.Spinner01);
// Step 2: Create and fill an ArrayAdapter with a bunch of "State" objects
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, new State[] {
new State(1, "Minnesota", "MN"),
new State(99, "Wisconsin", "WI"),
new State(53, "Utah", "UT"),
new State(153, "Texas", "TX")
});
// Step 3: Tell the spinner about our adapter
spinner.setAdapter(spinnerArrayAdapter);
Bạn có thể lấy mục được chọn như sau:
State st = (State)spinner.getSelectedItem();
Và bây giờ bạn có một lớp Java phù hợp để làm việc. Nếu bạn muốn chặn khi giá trị spinner thay đổi, chỉ cần triển khai OnItemSelectedListener và thêm các phương thức thích hợp để xử lý các sự kiện.
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// Get the currently selected State object from the spinner
State st = (State)spinner.getSelectedItem();
// Now do something with it.
}
public void onNothingSelected(AdapterView<?> parent)
{
}
Bạn có thể tìm thấy toàn bộ hướng dẫn ở đây: http://www.katr.com/article_android_spinner01.php
ngay cả khi nó không hoạt động ... tôi thích sự đơn giản của ý nghĩ rằng – kritzikratzi