不要将微调器视为按钮,按钮具有 onClick 事件。Spinners 有 onItemSelected 事件。
您应该像这样捕获 Spinner 的 onItemSelected 事件:
import android.widget.AdapterView;
Spinner productname_spinner =(Spinner) findViewById(R.id.your_spinner);
productname_spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
System.out.println(item.toString()); //prints the text in spinner item.
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
在 Kotlin 中,类似于以下内容:
mySpinner.onItemSelectedListener = object: OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
// Do nothing
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selection = parent?.getItemAtPosition(position)
viewModel.updateSelection(selection as String)
}
}