简体   繁体   中英

Three Buttons OnClickListener Android App

I have been trying to built a Math Flash Card App, the user inputs two numbers and then chooses one button depending if it wants the numbers add, subtract or multiply.

Image: http://i.stack.imgur.com/83FdN.png

The problem seem to be the OnClickListener. I have created other projects with one button and they work perfectly but with two buttons i don't know how to do it.

I have tried:

I have taken the button code out and run it and then it works. I don't know what else to do.

This is the last code that I have tried just trying with one button, app still force closed.

public class MainActivity extends ActionBarActivity implements OnClickListener{

int num1, num2, total;

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

    final EditText txtInt1 = (EditText)findViewById(R.id.txtInt1);
    final EditText txtInt2 = (EditText)findViewById(R.id.txtInt2);
    final TextView result = (TextView) findViewById(R.id.txtResult);

    num1 = Integer.parseInt(txtInt1.getText().toString());
    num2 = Integer.parseInt(txtInt2.getText().toString());

    final Button btnAddition = (Button) findViewById(R.id.btnAddition);
    Button btnSubstraction = (Button) findViewById(R.id.btnSubstraction);
    Button btnMultiplication = (Button) findViewById(R.id.btnMultiplication);
    /*
    btnSubstraction.setOnClickListener(this);      
    btnAddition.setOnClickListener(this); 
    btnMultiplication.setOnClickListener(this); */

    btnAddition.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v == btnAddition){

                if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
                    Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20", 
                            Toast.LENGTH_SHORT).show();
                }
                else {
                    total = num1+num2;
                    result.setText(num1+" + "+num2+" = "+total);
                } 
            }

        }
    });

Thank you!

Its better to move them to a single OnClick block of code . Check whether the v.getId() is the button id . Try by changing the code to

btnSubstraction.setOnClickListener(this);      
btnAddition.setOnClickListener(this); 
btnMultiplication.setOnClickListener(this);
}

 @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnAddition){

            if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
                Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20", 
                        Toast.LENGTH_SHORT).show();
            }
            else {
                total = num1+num2;
                result.setText(num1+" + "+num2+" = "+total);
            } 
        }


    }
});

Since you are implementing OnClickListener, it is required that you have the Override method onClick(View arg). By using switches you can setup individual cases for each button you want clickable actions for. Here are the steps

1) After instantiation of button widgets: Set onClickListener to each button widget

btnSubstraction.setOnClickListener(this);      
btnAddition.setOnClickListener(this); 
btnMultiplication.setOnClickListener(this);

2) Create your cases in onClick() method: Make sure that this is outside of your onCreate()

@Override
public void onClick(View v) {
   switch (v.getId()) {
   case R.id.btnAddition:
      // do some action for addition
      break;
   case R.id.btnSubstraction:
      // do some action for substraction
      break;
   case R.id.btnMultiplication:
      // do some action for multiplication
      break;
   default:
      break;
   }
}

3) Be sure that you implement OnClickListener

For a great tutorial on buttons you should check out http://ljtatum.blog.com/buttons/ . You can download free example code. But what I have posted above will work for you. Cheers!

Have you tried setting Logs? u can do this by: Log.e("TAG","MSG");

Then you can watch the LogCat and hunt the error down! ;)

I would implement the other Buttons exactly like you did your first one with the anonymous inner class.

btnSubstraction.setOnClickListener(new OnCLickListener() {
    @Override
    public void onClick(View v){
        Your Code goes here or u trigger another Method for readability for example:
        Substraction();

        ...

You should keep an Eye on the ID of the Buttons: R.findViewById...

But you don't even need this if you trigger the onClick on the buttonobject. ;) Yeah I guess that's it, try to leave the:

if(v==btnAddition)

The System already knows this by triggering the onClick over the buttonObject.

SO your code should go like this:

btnAddition.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
                Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20", 
                        Toast.LENGTH_SHORT).show();
            }
            else {
                total = num1+num2;
                result.setText(num1+" + "+num2+" = "+total);
            } 
        }
    }
});

btnSubstraction.setOnClickListener(new OnCLickListener() {
        @Override
        public void onClick(View v){
        //Substractioncode here
        }
});

What DaveS. is saying is that you are probably getting an exception in onCreate() on these two lines

num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());

these should be moved to the onClick() because in onCreate() they have not yet been given values so you will get a NumberFormatException . You also should do some error-checking such as

try {
    num1 = Integer.parseInt(txtInt1.getText().toString());
    num2 = Integer.parseInt(txtInt2.getText().toString());
} catch (NumberFormatException e) {
     // log the error and possibly print a message to the user
}

You should always post your stacktrace when your app crashes so we can find the answer easily. The issue with the code you posted is not due to the way you are setting the OnClickListener which is what you indicated.

This SO answer shows how to set the OnClickListener for Buttons . All will work fine so you decide which works best for you.

You are trying to getText and convert that string in int in onCreate() . In onCreate() you will get "" which is a blank string while you trying to convert it you will get a NumberFormatException . Solution is move these two inside onClick method of button .

num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM