在Spinner上设置一个默认选项可以解决这个问题。下面是示例代码:
在你的activity_main.xml中添加一个Spinner元素:
在MainActivity.java中添加以下代码:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner spinner;
String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
spinner.setSelection(0, false); //设置默认选项
}
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
String selected = parent.getItemAtPosition(position).toString();
Toast.makeText(this, selected, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView> parent) {
//无操作
}
}
在这个例子里,我们通过spinner.setSelection(0, false);
将第一个选项设为默认选项,并且不触发onItemSelected()
方法。这将导致Spinner在启动时就有一个默认选项。如果你想要Spinner在启动时选中一个特定的选项,请将参数0改为你想要选中的选项索引。