如何捕获onClick事件在Android中的微调(How to capture onClick e

2019-06-23 17:51发布

我想,当用户选择一个微调值来捕捉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事件?

Answer 1:

而不是设置微调的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;
        }
    }
};


Answer 2:

不要把一个微调就像一个按钮,按钮具有的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) {
    }
});

在科特林,类似以下内容:

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)
    }
}


文章来源: How to capture onClick event in Android for a spinner