How to add event listener to a spinner in Android?

To add an event listener, you can use the setOnItemSelectedListener() method to set the listener.

First, locate your Spinner object in your code. Then use the setOnItemSelectedListener() method and pass an AdapterView.OnItemSelectedListener object as a parameter.

Here is a sample code:

Spinner spinner = findViewById(R.id.spinner);

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // 当选定项发生改变时触发此方法
        String selectedItem = parent.getItemAtPosition(position).toString();
        Toast.makeText(getApplicationContext(), "选中项: " + selectedItem, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // 当没有选定项时触发此方法
    }
});

In the example above, the onItemSelected() method is triggered when a selected item changes. You can add the operations you want to perform inside this method. The onNothingSelected() method is triggered when no item is selected.

Remember to modify the reference to the spinner object according to your actual code.

bannerAds