Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture onClick event in Android for a spinner

I want to capture the onClick event when the user selects a spinner value.

I've tried implementing OnClickListener and using the following code:

@Override
public void onClick(final View view) {
  if (view == countrySpinner) {
    Toast.makeText(this, "Override OK!", 3);
  }
}

And binding with:

countrySpinner.setOnClickListener(this);

This compiles, but I get a RuntimeException advising me to use OnItemClickListener rather than OnClickListener for an AdapterView.

How can I capture that onClick event?

like image 750
tacos_tacos_tacos Avatar asked Apr 18 '12 15:04

tacos_tacos_tacos


2 Answers

Instead of setting the spinner's OnClickListener,try setting OnTouchListener and OnKeyListener.

spinner.setOnTouchListener(spinnerOnTouch);
spinner.setOnKeyListener(spinnerOnKey);

and the listeners:

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;
        }
    }
};
like image 85
ValayPatel Avatar answered Oct 06 '22 01:10

ValayPatel


Don't treat a spinner like a button, buttons have onClick events. Spinners have onItemSelected events.

You should be capturing the Spinner's onItemSelected event like this:

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

In Kotlin, similar to the following:

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)
    }
}
like image 43
Eric Leschinski Avatar answered Oct 06 '22 00:10

Eric Leschinski