Skip to content
Advertisement

Button setOnClickListener method is not invoked

The below is the sample code I’m trying to get the selected value from spinner on setOnClickListener method for the Button validateUser.

    public class MainActivity extends Activity implements  AdapterView.OnItemSelectedListener {
      private Button validateUser;
      private Spinner userTypeSpinner;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userTypeSpinner=(Spinner)findViewById(R.id.userTypeSpinner);
        validateUser= (Button) findViewById(R.id.userValidate);

        validateUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Button is Selected", Toast.LENGTH_SHORT);
            }
        });



        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.userTypeArray, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        userTypeSpinner.setAdapter(adapter);
        userTypeSpinner.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        String item = adapterView.getItemAtPosition(i).toString();

        Toast.makeText(adapterView.getContext(), "Selected: " + item, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}

Advertisement

Answer

Toast needs to be shown. use .show() at the end.

Toast.makeText(getApplicationContext(), "Button is Selected", Toast.LENGTH_SHORT).show();

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement