15

我想在用户选择微调器值时捕获 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 事件?

4

3 回答 3

23

尝试设置 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;
        }
    }
};
于 2012-04-18T15:52:22.487 回答
15

不要将微调器视为按钮,按钮具有 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)
    }
}
于 2014-11-03T00:19:43.980 回答
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();
});
于 2019-08-13T13:28:42.847 回答