计算器有多个onClick功能吗?

时间:2019-06-25 07:35:09

标签: java android

https://imgur.com/a/2UyKR8r

public class MainActivity extends AppCompatActivity {

    int c,d;
    float x,y,z,a;
    EditText ed1,ed2;
    TextView t1;
    Button b1,b2,b3,b4;

    public void add(View v){

       ed1 =  findViewById(R.id.editText);

       ed2 =  findViewById(R.id.editText2);

       t1  =  findViewById(R.id.textView);

       b1    =  findViewById(R.id.button);
       b2    =  findViewById(R.id.button2);
       b3    =  findViewById(R.id.button3);
       b4    =  findViewById(R.id.button4);


       c = Integer.parseInt(ed1.getText().toString());

       d = Integer.parseInt(ed2.getText().toString());

       x = c + d;

       t1.setText(String.valueOf(x));
    }
    public void sub(View v){

        y = c-d;
        t1.setText(String.valueOf(y));
    }
    public void mul(View v){

        z = c*d;
        t1.setText(String.valueOf(z));
    }
    public void div(View v){

        a = c/d;
        t1.setText(String.valueOf(a));
    }

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

    }
}

单击“减”,“乘”,“除”时,应用崩溃。

但是,如果我先进行加法运算,然后单击任何其他功能,它将正常工作,这只是在第一次单击按钮时。检查图像。

2 个答案:

答案 0 :(得分:1)

您正在使用add方法初始化视图。您应该使用onCreate方法。 这就是为什么如果您先单击添加按钮,它就会起作用的原因。

public void add(View v){
   c = Integer.parseInt(ed1.getText().toString());
   d = Integer.parseInt(ed2.getText().toString());
   x = c + d;
   t1.setText(String.valueOf(x));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ed1 = findViewById(R.id.editText);
    ed2 = findViewById(R.id.editText2);
    t1 = findViewById(R.id.textView);
    b1 = findViewById(R.id.button);
    b2 = findViewById(R.id.button2);
    b3 = findViewById(R.id.button3);
    b4 = findViewById(R.id.button4);
}

编辑: 您仅在add方法中从EditText获取值。您应该为其余操作添加以下两行:

c = Integer.parseInt(ed1.getText().toString());
d = Integer.parseInt(ed2.getText().toString());

答案 1 :(得分:0)

由于NullPointerException null object reference尚未引用,您确实会崩溃(t1,因此必须在add()方法中调用onCreate

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