先Adapter,后setSelection()。
使用
- xml布局,以dialog形式,弹出对话框选择
<Spinner
android:id="@+id/spinner
android:layout_width="match_parent"
android:layout_height="wrap_conten"
android:background="@null"
android:gravity="right"
android:spinnerMode="dialog" />
- res / layout / spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/checkedTextViewCustom"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:ellipsize="marquee"
android:singleLine="true"
android:textAlignment="inherit"
android:textSize="10sp" />
- activity
List<String> xxx = new ArrayList<>();
xxx.add("选项A");
xxx.add("选项B");
xxx.add("选项C");
...
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.spinner_item, xxx);
state.setAdapter(adapter);
state.setSelection(int n); //开局选一个,或者不写,默认第一行
state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
...
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
...
}
});