2020/4/10安卓开发:Spinner下拉框

  • layout中定义组件

<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

</Spinner>

  • 使用数组为spinner静态赋值

在valuse下建立arrays.xml

定义数组元素赋值(只能用string数组)

<string-array name="spinner_string">
<item>赵丽颖</item>
<item>迪丽热巴</item>
<item>杨超越</item>
</string-array>
使用spinner的entries属性
<Spinner
android:entries="@array/spinner_string"
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
  • 使用适配器

String[] strings={"赵丽颖","迪丽热巴","杨春雨"};
Spinner spinner=(Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinnerintem ,strings);
spinner.setAdapter(adapter);
说明1:
R.layout.spinnerintem为sprinner选中的item的布局  可通过来设置item的文本信息(比如居中 字体大小等)  注意用TextView布局
<?xml version="1.0" encoding="utf-8"?>
<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"
>

</TextView>

说明2:
strings为itme的文本信息
说明3:可以使用
ArrayAdapter<String>  和  ArrayAdapter<Integer> 等  但是对应的属于类型要与泛型对应
  • 设置每个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的文本格式 字体大小 居中等


 

 

 







 

猜你喜欢

转载自www.cnblogs.com/miwujun/p/12670872.html