Spinner 类图
android.widget
类 Spinner
java.lang.Object
android.view.View
android.view.ViewGroup
android.widget.AdapterViewandroid.widget.AbsSpinner
android.widget.Spinner
Spinner 意指下拉列表组件。
以下为android官网文档内容。
布局文件中加入Spinner元素标签
To populate the spinner with a list of choices, you then need to specify a
为了给spinner增加选择项,你需要在你的Activity或者Fragment中使用一个特定的SpinnerAdapter对象作为数据源绑定到Spinner对象上。
The choices you provide for the spinner can come from any source, but must be provided through an
虽然你可以给spinner提供任一数据源,但是这种数据源必须是实现SpinnerAdapter接口的。例如ArrayAdapter。如果选择从数据库中查询得到数据,那么你可以使用CursorAdapter这种Adapter作为数据源。
可以使用string数组。
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
With an array such as this one, you can use the following code in your
如果使用string数组,你需要在你的Activity或者Fragment中使用ArrayAdapter。
Spinner spinner =(Spinner) findViewById(R.id.spinner);//Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);//Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//Apply the adapter to the spinner
spinner.setAdapter(adapter);
静态方法 createFromResource(Context context, int textArrayResId, int textViewResId )
参数context 这里使用this 意指Activity
参数textArrayResId 这里使用R.array.plants_array 数据来源
参数textViewResId 这里使用android.R.layout.simple_spinner_item(android提供 也可以自己定制) Spinner的布局样式
You should then call
如何响应用户的选择,实现OnItemSelectedListener接口
public class SpinnerActivity extends Activity implementsOnItemSelectedListener {
...public void onItemSelected(AdapterView>parent, View view,int pos, longid) {//An item was selected. You can retrieve the selected item using//parent.getItemAtPosition(pos)
}public void onNothingSelected(AdapterView>parent) {//Another interface callback
}
}
其中此接口需要实现其中的两个方法
Then you need to specify the interface implementation by calling
Spinner spinner =(Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);