android spinner第三方库,Android Spinner控件详解

本文详细介绍了Android Spinner组件,它是下拉列表组件。Spinner的数据源可以通过实现SpinnerAdapter接口的Adapter来绑定,如ArrayAdapter或CursorAdapter。文章展示了如何在布局文件中添加Spinner,如何使用ArrayAdapter填充数据,以及如何实现OnItemSelectedListener监听用户选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值