1. 关键点
1). Spinner的菜单显示方式
它有两种显示形式,一种是下拉菜单,一种是弹出框,菜单显示形式是spinnerMode属性决定的:
android:spinnerMode="dropdown"
android:spinnerMode="dialog"
下面是Theme.Light和Theme.Holo.Light下Spinner在不同模式下的效果对比图。
2). 在Spinner的xml属性
其实上面已经提到了Spinner的两个属性:
1 entries: 直接在xml布局文件中绑定数据源(可以不设置,即可以在Activity中动态绑定)
2 spinnerMode: Spinner的显示形式
2. 代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example2.spinner.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Spinner android:layout_width="wrap_content" android:layout_height="wrap_content" android:entries="@array/language" android:id="@+id/spinner"></Spinner> </android.support.constraint.ConstraintLayout>
esvaluesarrays.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="language"> <item >C语言</item> <item >JAVA</item> <item >C++</item> <item >PHP</item> <item >其他</item> </string-array> </resources>
MainActivity.java
package com.example2.spinner; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Spinner spinner = (Spinner)findViewById(R.id.spinner); //设置监听 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { String[] res = getResources().getStringArray(R.array.language); Toast.makeText(MainActivity.this,"点击为"+res[i],Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } }