An Android button listener example (OnClickListener, Spinner, Intent)

Here’s a little snippet of Android code that I want to remember:

private void addButtonListener(Button playGameButton) {
    playGameButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String yourTeamName = String.valueOf(mYourTeamSpinner.getSelectedItem());
            String opponentTeamName = String.valueOf(mComputerTeamSpinner.getSelectedItem());
            Intent intent = new Intent(getActivity().getApplicationContext(), PlayGameActivity.class);
            intent.putExtra(YOUR_TEAM_NAME, yourTeamName);
            intent.putExtra(OPPONENT_TEAM_NAME, opponentTeamName);
            startActivity(intent);
        }
    });
}

It shows:

  • How to add a listener to an Android button
  • How to respond to a button tap event
  • How to get the display values from an Android Spinner (two spinners, actually)
  • How to create an Intent
  • How to add “extras” to an Intent
  • How to start a new Activity with that Intent

If you ever need to do any of those things, I hope this code snippet is helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.