天天看点

AS写简易计算器

20180610

以mimu9的简易计算器为demo

1、布局

①排布

AS写简易计算器

AS提供这几种布局,在这个APP中选择了RelativeLayout为主布局,然后把button放在linearlayout(horizontal)中

这样可以设置为一行一行地编辑各个button,更容易对齐及寻找

②方向锁定

在AndroidMainfest.xml中添加

android:screenOrientation="portrait"      

则无论手机如何变动,拥有这个属性的activity都将是竖屏显示。

android:screenOrientation="landscape"      

横屏显示

2、实例化button

①定义button对应的id的类型

Button btn_0 ;      

②实例化

btn_0 = (Button) findViewById(R.id.btn_0) ;      

③设置按钮点击事件

btn_0.setOnClickListener(this);      

3、点击按钮后

switch (v.getId()) {
    case R.id.btn_0:      

②运算

String exp = et_input.getText().toString();
if (exp == null||exp.equals("")){
    return;
}
if(!exp.contains(" ")) {
    return;
}
if (clear_flag){
    clear_flag = false ;
    return;

}
clear_flag = true ;
double result = 0 ;
String s1 = exp.substring(0,exp.indexOf(" ")); //运算符前面的字符串
String op = exp.substring(exp.indexOf(" ")+1,exp.indexOf(" ")+2) ;
String s2 = exp.substring(exp.indexOf(" ")+3) ;
if (!s1.equals(" ")&&!s2.equals(" ")){
    double d1 = Double.parseDouble(s1) ;
    double d2 = Double.parseDouble(s2) ;
    if (op.equals("+")){
        result = d1 + d2 ;

    }else  if (op.equals("-")){
        result = d1 - d2 ;

    }else  if (op.equals("*")){
        result = d1 * d2 ;

    }else  if (op.equals("/")){
        if(d2 == 0){
            result = 0 ;
        }else {
            result = d1/d2 ;
        }
    }
    if (s1.contains(".")&&s2.contains(".")) {
        int r = (int) result;
        et_input.setText(r+"");
    }else {
        et_input.setText(result+"");

    }
}else if (!s1.equals("")&&s2.equals("")){
    et_input.setText(exp);
}else if (s1.equals("")&&!s2.equals("")){
    double d2 = Double.parseDouble(s2) ;
    if (op.equals("+")){
        result = 0 + d2 ;

    }else  if (op.equals("-")){
        result = 0 - d2 ;

    }else  if (op.equals("*")){
        result = 0 ;

    }else  if (op.equals("/")){
        result = 0 ;
    }
    if (s2.contains(".")) {
        int r = (int) result;
        et_input.setText(r+"");
    }else {
        et_input.setText(result+"");
    }
}else {
    et_input.setText("");

}      

把在显示屏中的字符串进行解析并进行运算并把结果输出在显示屏。

https://github.com/Eva-here/Calculator

as