实现安卓Spinner控件hint提示效果
程序员文章站
2022-07-04 18:50:08
...
效果图:
1.定义一个Spinner控件:
<Spinner android:layout_width="150dp" android:layout_height="match_parent" android:id="@+id/spinner_car">
2.Activity代码:
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); }
/** * 定义一个Myadapter类继承ArrayAdapter * 重写以下两个方法 * */ class Myadapter<T> extends ArrayAdapter{ public Myadapter(@NonNull Context context, int resource, @NonNull List<T> objects) { super(context, resource, objects); } @Override public int getCount() { //返回数据的统计数量,大于0项则减去1项,从而不显示最后一项 int i = super.getCount(); return i>0?i-1:i; } }