编辑文本自动计算

时间:2017-05-10 20:18:20

标签: java android

我正在创建一个计算具体音量的应用。我有3个editText字段,但我希望其中一个文本字段在输入数据时自动从英尺到英寸进行计算。要做到这一点,你只需将字段中的任何数字除以12,但如何编写代码来做到这一点?

这是我的Java代码:

public class Calculation extends Activity implements View.OnClickListener {

    private Button aButton;
    private TextView tvAnswer;
    private EditText input1, input2, input3;


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

        tvAnswer = (TextView) findViewById(R.id.answer);
        input1 = (EditText) findViewById(R.id.length);
        input2 = (EditText) findViewById(R.id.width);
        input3 = (EditText) findViewById(R.id.thickness);
        aButton = (Button) findViewById(R.id.button);
        aButton.setOnClickListener(this);
    }

    public void onClick(View v) {

        Double inputt1 = input1.getText().toString().equals("") ? 0 : Double.valueOf(input1.getText().toString());
        Double inputt2 = input2.getText().toString().equals("") ? 0 : Double.valueOf(input2.getText().toString());
        Double inputt3 = input3.getText().toString().equals("") ? 0 : Double.valueOf(input3.getText().toString());

        switch (v.getId()){
            case R.id.button:
       tvAnswer.setText(Double.toString(inputt1*inputt2*inputt3));
            break;
        default:
            break;

2 个答案:

答案 0 :(得分:0)

  

我希望其中一个文本字段从英尺到英寸进行计算   输入数据时自动

您需要的是TextWatcher

实施例

 public TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            // do calculation here
            calculation();
        }
    };

onCreate方法中,添加此

input1.addTextChangedListener(mTextWatcher);

答案 1 :(得分:0)

您必须将TextWatcher用于editText。

input1.addTextChangedListener(new TextWatcher() {
 @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            // Call method to calculate your value same way you do in onClick()
        }
    });