我想在用户选择微调器值时捕获onClick事件。
我已经尝试实现OnClickListener
并使用以下代码:
@Override
public void onClick(final View view) {
if (view == countrySpinner) {
Toast.makeText(this, "Override OK!", 3);
}
}
和绑定:
countrySpinner.setOnClickListener(this);
这编译,但我得到一个RuntimeException
建议我使用OnItemClickListener
而不是OnClickListener
为AdapterView
。
如何捕获onClick事件?
不要设置微调器的OnClickListener,而是尝试设置OnTouchListener和OnKeyListener。
spinner.setOnTouchListener(spinnerOnTouch);
spinner.setOnKeyListener(spinnerOnKey);
和听众:
private View.OnTouchListener spinnerOnTouch = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
//Your code
}
return false;
}
};
private static View.OnKeyListener spinnerOnKey = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
//your code
return true;
} else {
return false;
}
}
};
不要像按钮那样对待微调器,按钮有onClick事件。旋转器具有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)
}
}