我试图制作一个简单的计算器,但由于某些原因,我无法得到结果 应用程序运行但是当我按下按钮时,没有按预期显示弹出结果。
以下是代码:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText number1EditText;
private EditText number2EditText;
private Button divideButton;
private Button multiplyButton;
private Button addButton;
private Button subtractButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1EditText = (EditText) findViewById(R.id.number1EditText);
number2EditText = (EditText) findViewById(R.id.number2EditText);
divideButton=(Button)findViewById(R.id.divideButton);
multiplyButton=(Button)findViewById(R.id.multiplyButton);
addButton=(Button)findViewById(R.id.addButton);
subtractButton=(Button)findViewById(R.id.subtractButton); }
public void onClick(View v){
switch (v.getId()){
case R.id.divideButton:
division();
break;
case R.id.multiplyButton:
multiplication();
break;
case R.id.addButton:
addition();
break;
case R.id.subtractButton:
subtraction();
break;} }
private void division(){
String number1 = number1EditText.getText().toString();
String number2 = number2EditText.getText().toString();
int answer = Integer.parseInt(number1)/Integer.parseInt(number2);
Toast.makeText(this,String.valueOf(answer), Toast.LENGTH_LONG).show();}
private void multiplication(){
String number1=number1EditText.getText().toString();
String number2=number2EditText.getText().toString();
int answer=Integer.parseInt(number1)*Integer.parseInt(number2);
Toast.makeText(this,String.valueOf(answer),Toast.LENGTH_LONG).show(); }
private void addition(){
String number1=number1EditText.getText().toString();
String number2=number2EditText.getText().toString();
int answer = Integer.parseInt(number1) + Integer.parseInt(number2);
Toast.makeText(this,String.valueOf(answer), Toast.LENGTH_LONG).show(); }
private void subtraction(){
String number1=number1EditText.getText().toString();
String number2=number2EditText.getText().toString();
int answer=Integer.parseInt(number1) - Integer.parseInt(number2);
Toast.makeText(this,String.valueOf(answer),Toast.LENGTH_LONG).show(); }}
答案 0 :(得分:2)
解决方案很简单,就在这里:
divideButton=(Button)findViewById(R.id.divideButton);
multiplyButton=(Button)findViewById(R.id.multiplyButton);
addButton=(Button)findViewById(R.id.addButton);
subtractButton=(Button)findViewById(R.id.subtractButton);
您找到按钮,但从未设置onCLickListener。添加以下代码:
divideButton.setOnClickListener(this);
multiplyButton.setOnClickListener(this);
addButton.setOnClickListener(this);
subtractButton.setOnClickListener(this);