我在微调器中添加了所有必要的项,但我想将第一个项设置为空默认项,如"选择类别"在项目的第一个位置。如何将第一个设置为空默认值?
这是我的代码
private Spinner customSpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
//CUSTOM SPINNER----------------------------------------------------------------------------
customSpinner=findViewById(R.id.customSpinner);
// create spinneritemlist for spinner
ArrayList<CustomItems> customList = new ArrayList<>();
customList.add(new CustomItems("Cat",R.drawable.ic_)); //30dp vector asset
customList.add(new CustomItems("Dog",R.drawable.ic_));
customList.add(new CustomItems("Elephant",R.drawable.ic_));
customList.add(new CustomItems("item 2",R.drawable.ic_));
customList.add(new CustomItems("item 3",R.drawable.ic_));
customList.add(new CustomItems("4",R.drawable.ic_));
customList.add(new CustomItems("5",R.drawable.ic_));
customList.add(new CustomItems("c",R.drawable.ic_));
customList.add(new CustomItems("shark",R.drawable.ic_));
customList.add(new CustomItems("Pet",R.drawable.ic_));
customList.add(new CustomItems("Toys",R.drawable.ic_));
customList.add(new CustomItems("Others",R.drawable.ic_));
// create Adapter for spinner
CustomAdapter customAdapter = new CustomAdapter(this, customList);
if (customSpinner != null) {
customSpinner.setAdapter(customAdapter);
customSpinner.setOnItemSelectedListener(this);
}
//CUSTOM SPINNER----------------------------------------------------------------------------
}
//CUSTOM SPINNER--------------------------------------------------------------------------------
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
CustomItems items = (CustomItems) adapterView.getSelectedItem();
Toast.makeText(this, items.getSpinnerText(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
//CUSTOM SPINNER--------------------------------------------------------------------------------
您可以尝试此方法为微调器实现占位符
ArrayList<CustomItems> customList = new ArrayList<>();
customList.add(new CustomItems("Cat",R.drawable.ic_)); //30dp vector asset
customList.add(new CustomItems("Dog",R.drawable.ic_));
customList.add(new CustomItems("Elephant",R.drawable.ic_));
customList.add(new CustomItems("Select Animal",R.drawable.ic_)); <- This
在您的CustomAdapter中覆盖getCount
方法
@Override
public int getCount() {
return customList.length - 1;
}
在您的onCreate函数中设置适配器之后
customSpinner.setSelection(customList.length - 1);