Creating A second Button In a "Main Menu" Activity

0 Ryan Kirk · May 21, 2015
I have a main menu with two buttons, one meant to take you to an "Addition" Class, which works, and one that is supposed to take you to a subtraction class. I can't seem to get both to work at the same time. Here's the code:

   
package com.example.kirky_000.madmath;
    
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Button;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.content.Context;
    import android.content.Intent;
    
    
    public class MainMenu extends ActionBarActivity {
        Button button;
        Button button2;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_menu);
            addListenerOnButton();
    }
    
        public void addListenerOnButton() {
    
            final Context context = this;
    
            button = (Button) findViewById(R.id.button);
            button2 = (Button) findViewById(R.id.button2);
    
    
            button.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
    
                    Intent intent = new Intent(context, Addition.class);
                    startActivity(intent);
    
                }
                button2.setOnClickListener(new OnClickListener() {
    
                    @Override
                    public void onClick(View arg0) {
    
                        Intent intent = new Intent(context, Subtraction.class);
                        startActivity(intent);
    
                    }
            });
    
        }

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · May 21, 2015
The reason is because you are doing something weird which is putting button 2's setOnClickListener within button.setOnClickListener.

In other words, you nested setting button2's listener inside button 1's setOnClickListener. These two methods should be used sequentially.

What it currently looks like:

button.setOnClickListener ...button2.setOnClickListener...;

What it should look like:


button.setOnClickListener ...;

button2.setOnClickListener ...;

How does this even load without an error?
  • 1

Java / Android Development

107,076 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator