Giới thiệu
Spinner là dropdown list cho phép chọn 1 item từ tập hợp. Bài viết hướng dẫn điền dữ liệu vào Spinner bằng ArrayAdapter.
Các bước thực hiện
Bước 1: Tạo project Android Studio
Bước 2: Layout activity_main.xml
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:prompt="@string/app_name" />
Bước 3: MainActivity.java - Thiết lập Adapter
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = findViewById(R.id.spinner);
ArrayList arrayList = new ArrayList<>();
arrayList.add("JAVA");
arrayList.add("ANDROID");
arrayList.add("C Language");
arrayList.add("CPP Language");
arrayList.add("Go Language");
arrayList.add("AVN SYSTEMS");
ArrayAdapter adapter = new ArrayAdapter<>(
this,
android.R.layout.simple_spinner_item,
arrayList
);
// Layout cho dropdown view
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// Xử lý sự kiện chọn item
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
String tutorialsName = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Đã chọn: " + tutorialsName, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView> parent) {
// Không chọn gì
}
});
}
}
Bước 4: Chạy thử
Spinner hiển thị danh sách, chọn item → Toast thông báo:

Các layout có sẵn cho Spinner
| Layout | Mô tả |
|---|---|
android.R.layout.simple_spinner_item | Item hiển thị khi Spinner đóng (1 dòng text). |
android.R.layout.simple_spinner_dropdown_item | Item trong danh sách thả xuống (có radio button). |
| Custom layout | Tự tạo XML cho item phức tạp (image + text). |
Spinner với Custom Adapter (hình ảnh + text)
// Model
class SpinnerItem {
String name;
int iconResId;
// constructor, getter...
}
// Custom Adapter extends BaseAdapter
class SpinnerAdapter extends BaseAdapter {
List items;
Context context;
// implement getView, getDropDownView với ViewHolder
}
// Sử dụng
SpinnerAdapter adapter = new SpinnerAdapter(this, items);
spinner.setAdapter(adapter);
Lưu ý
- Spinner không hỗ trợ multi-select (chỉ chọn 1).
onItemSelectedgọi ngay khi setAdapter (position 0) → xử lý logic cẩn thận.- Để đặt giá trị mặc định:
spinner.setSelection(position). - Hiện nay nhiều app dùng **Material Design Exposed Dropdown Menu** (TextInputLayout + AutoCompleteTextView) thay Spinner cũ.