效果图:
1.定义一个Spinner控件:
<Spinner
android:layout_width="150dp"
android:layout_height="match_parent"
android:id="@+id/spinner_car">
Spinner spinner_car;
List<String> cars = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner_car = findViewById(R.id.spinner_car);
myadapter();
}
public void myadapter()
{
cars.add("1号爪黄飞电");
cars.add("2号卷毛赤兔");
cars.add("3号绝影");
cars.add("请选择车辆");
Myadapter myadapter = new Myadapter(thisR.layout.support_simple_spinner_dropdown_item,cars);
spinner_car.setAdapter(myadapter);
spinner_car.setSelection(cars.size()-1,true);
}
class Myadapter<T> extends ArrayAdapter{
public Myadapter(@NonNull Context context, int resource, @NonNull List<T> objects) {
super(context, resource, objects);
}
@Override
public int getCount() {
int i = super.getCount();
return i>0?i-1:i;
}
}