Android计算器:小数位的按钮

时间:2012-08-13 12:00:37

标签: android calculator

我是Android开发的新手,目前正在学习设计基本的计算器应用程序。我已经自行设计了布局,但是从不同网站获取了主要活动代码,用于0到9 +, -, *, /的操作,并且在合并后,它们工作正常。

但是,我确实想用小数点函数进一步修改MainActivity。 使用“current = current * 10 + number”可以在屏幕上正确显示整数,例如53 = 5 * 10 + 3;

我在想用循环函数对小数点应用相同的方法,这样的想法: 1. current = current +如果按下点按钮则剩余 2.创建一个整数i,一旦点击任何数字按钮,我增加1 3.以便例如输入5.3,i = 1,它将= 5 + 3 /(10 ^ i)= 5.3 4. 5.3循环到这里,然后例如输入为5.39,现在i = 2,它将= 5.3 + 9 /(10 ^ i)= 5.39

问题>> * 然而......真的......我很新鲜,我不知道如何设计十进制按钮的编码,是否有人可以建议代码? *首先忽略以下插件如果要检测错误(例如,如果输入两次或更多点,则删除第二个点,在0前面添加.,如果输入.5,则输入

按钮ID如下所示,一旦点击就会引用DecimalClickEvent       按钮b_decimal =(按钮)findViewById(R.id.decimal);       b_decimal.setOnClickListener(new DecimalClickEvent(???));}

许多人提前感谢!!下面附有代码供参考和您的意见:

========================= MainActivity.java =================== ==================

package com.trial.newcalculator;

import java.io.Serializable;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

@SuppressLint("ParserError")
public class MainActivity extends Activity {
    State s;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        s = new State();

        int[] opNumbers = new int[] { 
                R.id.zero,
                R.id.one,
                R.id.two,
                R.id.three,
                R.id.four,
                R.id.five,
                R.id.six,
                R.id.seven,
                R.id.eight,
                R.id.nine,     
        };

        final TextView textView = (TextView) findViewById(R.id.ansEditText);
        for (int i = 0; i < 10;i++){
            final Button button = (Button) findViewById(opNumbers[i]);        
            button.setOnClickListener(new NumberClickEvent(textView,s,i));          
        }

      int[] opButtons = new int[] { R.id.add, R.id.subtract, R.id.multiply, R.id.divide };
      State.Operation[] states = new State.Operation[] {
                State.Operation.PLUS, 
                State.Operation.MINUS,
                State.Operation.MULTIPLY, 
                State.Operation.DIVIDE};

        for(int i = 0; i < opButtons.length;i++){
        Button b_op = (Button) findViewById(opButtons[i]);
        b_op.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
        }

// Memory functions
        int[] memButtons = new int[] { R.id.MC, R.id.MR, R.id.Mdeduct, R.id.Mplus};
        State.Operation[] mstates = new State.Operation[] {
                State.Operation.MEMORYCLEAR, 
                State.Operation.MEMORYCALL,
                State.Operation.MEMORYMINUS, 
                State.Operation.MEMORYPLUS};

        for(int i = 0; i < memButtons.length;i++){
        Button b_mem = (Button) findViewById(memButtons[i]);
        b_mem.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
        }
//  Memory functions    

//decimal
//      Button b_decimal = (Button) findViewById(R.id.decimal);
//      b_decimal.setOnClickListener(new DecimalClickEvent(textView, s, "."));   
//decimal

        Button b_eq = (Button) findViewById(R.id.equal);
        b_eq.setOnClickListener(new EqualClickEvent(textView, s));

        Button b_op = (Button) findViewById(R.id.ac);
        b_op.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                s.clear();
                textView.setText(s.getDisplay());
            }
        });               
    }      
@Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putSerializable("STATE", s);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        Serializable serializable = savedInstanceState.getSerializable("STATE");
        if(serializable!= null){
            s = (State) serializable;
        }
    }

    public void onPause(){
         super.onPause();
    }

}

=============================== State.java ============= =====================

package com.trial.newcalculator;

import java.io.Serializable;
import android.text.Editable;
import android.widget.TextView;

public class State implements Serializable {
    private static final long serialVersionUID = -1231231231231233L;
    public TextView output;
    public enum Operation {     
        PLUS,       
        MINUS,      
        MULTIPLY,       
        DIVIDE,     
        MEMORYPLUS,
        MEMORYMINUS,
        MEMORYCALL,
        MEMORYCLEAR,
    }   
    public enum IOState{        
        INPUTTING,      
        DISPLAY_RESULT, 
    }   
    private Double accu = null; 
    private double current = 0; 
    private double memory = 0;
    private Operation currentOp = null; 
    private IOState currentState = IOState.INPUTTING;   
    public Operation getCurrentOp() {       
        return currentOp;   
    }   
    public void setCurrentOp(Operation currentOp) {     
        if (currentState == IOState.INPUTTING){         
            if (accu != null && this.currentOp != null ){calculateResult(); 
            }
            else{accu = Double.valueOf(current);current = 0;
            }
        }
        this.currentOp = currentOp;     
        if (currentState == IOState.INPUTTING){
            currentState = IOState.DISPLAY_RESULT;
        }   
    }   
    private void calculateResult() {
        double res = accu.doubleValue();
        switch (currentOp) {
            case PLUS:
                res += current;
                break;
            case MINUS:
                res -= current;
                break;
            case MULTIPLY:
                res *= current;
                break;
            case DIVIDE:
                res /= current;
                break;
            case MEMORYPLUS:
                memory += current;
                break;
            case MEMORYMINUS:
                memory -= current;
                break;
            case MEMORYCLEAR:
                memory = 0;
                break;
            case MEMORYCALL:
                current = memory;
                break;
        }
        accu = Double.valueOf(res);
        current = 0;
    }
    public void number(int number) {
        if (currentState == IOState.INPUTTING){
            current = current *10 + number;
        }
        else if(currentState == IOState.DISPLAY_RESULT){
            currentState = IOState.INPUTTING;
            current = number;
        }
    }
    public String getDisplay() {
        String res;
        Double d = getCurrentDisplayValue();
        double doubleValue = d.doubleValue();
        int intVal = (int)doubleValue;
        if (intVal == doubleValue){
            res = Integer.toString(intVal);
            }
        else{
            res = d.toString();
            }
        return res;
    }
    private Double getCurrentDisplayValue() {
        Double d = accu;
        if (currentState == IOState.INPUTTING){
            d = Double.valueOf(current);
        }
        return d;
    }
    public void clear() {
        accu = null;
        currentState = IOState.INPUTTING;
        currentOp = null;
        current = 0;
    }

    public void equal() {
        if (accu == null || currentOp == null){
            return;
        }
        calculateResult();
        currentState = IOState.DISPLAY_RESULT;
        currentOp = null;
        current = getCurrentDisplayValue(); 
        }
}

==================== OperationClickEvent.java ======================== =======

package com.trial.newcalculator;

import com.trial.newcalculator.State.Operation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

final class OperationClickEvent implements OnClickListener {
    private State s;
    private TextView textView;
    private Operation op;


    public OperationClickEvent(TextView textView, State s, State.Operation op) {
        super();
        this.op = op;
        this.s = s;
        this.textView = textView;
    }


    public void onClick(View v) {
        s.setCurrentOp(op);
        textView.setText(s.getDisplay());
    }
}

================= EqualClickEvent.java =========================== ============

package com.trial.newcalculator;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

final class EqualClickEvent implements OnClickListener {
    private State s;
    private TextView textView;


    public EqualClickEvent(TextView textView, State s) {
        super();
        this.s = s;
        this.textView = textView;
    }


    public void onClick(View v) {
        s.equal();
        textView.setText(s.getDisplay());
    }
}

====================== NumberClickEvent.java ====================== ============

package com.trial.newcalculator;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

final class NumberClickEvent implements OnClickListener {
    private int number;
    private State s;
    private TextView textView;


    public NumberClickEvent(TextView textView, State s, int number) {
        super();
        this.number = number;
        this.s = s;
        this.textView = textView;
    }


    public void onClick(View v) {
        s.number(number);
        textView.setText(s.getDisplay());
    }
}

2 个答案:

答案 0 :(得分:0)

我建议你不要为负点击事件和doublezeroclickevent创建新类,而是在点击特定按钮时获取他们的id并执行正确的功能。

答案 1 :(得分:0)

每个OnClickListener都可以是默认的匿名类,只能由一个按钮触发。 所以不需要将它们命名为“NegativeClickEvent”,“DoublezeroClickEvent”等等。

如果“。”,你可以保留一个布尔变量。被压了,只有不接受另一个。 如果你想要一个可用的计算器,你也需要一个“退格”按钮。请注意,可能会删除该点。 (需要跟踪其位置)。

对于前导0,您可以使用简单的“如果先按下点,插入0。”。

有很多方法可以实现您想要的功能,但为了简单起见,只需处理您需要处理的案例。

实现它的其他方法可能包括Double.parseDouble(s)在每个按下的键上使用catch(NumberFormatException e),或者使用double作为缓冲区,并使用按钮直接对它执行数学运算(例如乘法)按10并在每个按钮上添加新数字) - 这将确保输入有效性而无需解析字符串,但实现起来更复杂。