重要属性和方法
- 属性
android:dropDownVerticalOffset:设置竖直偏移量 android:dropDownHorizontalOffset:设置水平偏移量 android:spinnerMode:设置下拉框的显示模式 - 方法
setPrompt():设置选项顶部提示文字 setAdapter():设置适配器 setSelection():设置当前默认选项
定义下拉框
<Spinner
android:id="@+id/spinner"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:dropDownVerticalOffset="50dp"
android:spinnerMode="dropdown">
</Spinner>
使用适配器实现选择功能
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner =findViewById(R.id.spinner);
String[] items={"选项1","选项2","选项3"};
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,items);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,items[position],Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
|