在Android中使用下拉列表控件通常有兩種方式:通過Spinner控件或AutoCompleteTextView控件。
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Spinner spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.items_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
// 處理選中項的操作
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// 未選中任何項的操作
}
});
<string-array name="items_array">
<item>選項1</item>
<item>選項2</item>
<item>選項3</item>
</string-array>
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.items_array, android.R.layout.simple_dropdown_item_1line);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
// 處理選中項的操作
}
});
<string-array name="items_array">
<item>選項1</item>
<item>選項2</item>
<item>選項3</item>
</string-array>
以上是使用Spinner和AutoCompleteTextView控件調用下拉列表的基本步驟,可以根據具體需求進行相應的調整。