先布置页面,也就是XML的代码,要使用Spinner标签,Spinner其实就是一个列表选择框。不过Android的列表选择框并不需要显示下拉列表,而是相当于弹出一个菜单供用户选择。
Spinner 与 Gallery 都继承了AbsSpinner,AbsSpinner 继承了AdapterView,因此它也表现出AdapterView的特征:只要为AdapterView提供Adapter即可
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="120dp"
android:layout_height="40dp"
android:gravity="center"
android:layout_marginBottom="8dp"
android:text="选择点餐桌台:"
android:textStyle="bold"/>
<Spinner
android:id="@+id/sp_ordering_chelduled"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textPersonName"
android:spinnerMode="dialog" />
</LinearLayout>
布置好页面就去Activity请求后台数据然后绑定:
- 根据Spinner声明的ID去获取Spinner的控件
Spinner spOrderingChelduled = findViewById(R.id.sp_ordering_chelduled);
- 请求后台去查询数据,获取到了数据就可以使用Arraydapter把数据绑定上去了
ArrayAdapter的理解:ArrayAdapter是BaseAdapter的一个具体实现,可直接使用泛型进行构造,能像List一样直接对Adapter进行增删操作,要显示一个数组,我们就用ArrayAdapter,数组适配器,数据的数据类型<>是String类型的,数据的数据类型还可以是其他的包括对象类。Android 中提供了很多适配器的实现类,其中我认为最好用的就是ArrayAdapter。它可以通过泛型来指定要适配的数据类型,然后在构造函数中把要适配的数据传入即可。ArrayAdapter有多个构造函数的重载,你应该根据实际情况选择最合适的一种。这里由于我们提供的数据都是字符串,因此将ArrayAdapter 的泛型指定为String,然后在ArrayAdapter的构造函数中依次传入当前上下文、ListView 子项布局的id,以及要适配的数据。注意我们使用了android.R.layout.simple_list_item_1 作为ListView 子项布局的id,这是一个Android 内置的布局文件,里面只有一个TextView,可用于简单地显示一段文本
- 绑定的效果图如下
补充扩展Spinner的点击事件:
spOrderingCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});