-
layout中定义组件
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
-
使用数组为spinner静态赋值
在valuse下建立arrays.xml
定义数组元素赋值(只能用string数组)
- 赵丽颖
- 迪丽热巴
- 杨超越
使用spinner的entries属性
android:entries="@array/spinner_string"
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
-
使用适配器
String[] strings={"赵丽颖","迪丽热巴","杨春雨"};
Spinner spinner=(Spinner)findViewById(R.id.spinner);
ArrayAdapteradapter=new ArrayAdapter (this,R.layout.spinnerintem ,strings);
spinner.setAdapter(adapter);
说明1:
R.layout.spinnerintem为sprinner选中的item的布局 可通过来设置item的文本信息(比如居中 字体大小等) 注意用TextView布局
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:gravity="center"
android:textSize="12dp"
>
说明2:
strings为itme的文本信息
说明3:可以使用
ArrayAdapter 和 ArrayAdapter 等 但是对应的属于类型要与泛型对应
-
设置每个item的监听器
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
TextView textView=(TextView)view;
Toast.makeText(MainActivity.this,textView.getText(),Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView> adapterView) {
}
});
说明:可以利用 TextView textView=(TextView)view;来设置每个itme的文本格式 字体大小 居中等