我想在用户选择微调器值时捕获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事件?
答案 0 :(得分:17)
尝试设置OnTouchListener和OnKeyListener,而不是设置微调器的OnClickListener。
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;
}
}
};
答案 1 :(得分:14)
不要像按钮那样对待微调器,按钮有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)
}
}
答案 2 :(得分:0)
我尝试使用以下代码实现OnItemSelectedListener
来获取Selected Spinner Value:
String selectAreaNameString;
AreaSpinner.setOnItemSelectedListener(AreaSpinnerSelected = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
selectAreaNameString = item.toString();
});