Using a TextWatcher on a EditText to calculate the total and sum total in real time in android?

一世执手 提交于 2019-12-06 00:50:43

Below is not the complete code, but that will give an idea of the implementation. You have to create a new method for calculation and displaying the result -

private void calculateAndShow(long wt, long rt, long mk){
        double NetRate = rt + mk;
        double Total = (NetRate / 10) * wt;

        // Change the value here
        barCode.setText(itembarcode);
        itemDesc.setText(itemdesc);
        weightLine.setText(weight);
        rateAmount.setText(rate);
        makingAmount.setText(making);
        netRate.setText(NetRate + "");
        itemtotal.setText(Total + "");

    }

Now add these lines outside of your method -

 private TextWatcher rateTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String rate = rateAmount.getText().toString();
            newRate = Double.parseDouble(rate);
            calculateAndShow(wt, newRate, mk);
        }
    };

    private TextWatcher makingAmountTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String makingAmount = makingAmount.getText().toString();
            newMK = Double.parseDouble(makingAmount);
            calculateAndShow(wt, rt, newMK);
        }
    };

And these textwatcher to your edittext like this one -

EditText rateAmount = new EditText(AddInvEst.this);
        rateAmount.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 0.5f));
        rateAmount.setGravity(Gravity.CENTER);
        rateAmount.addTextChangedListener(rateTextWatcher);


 EditText makingAmount = new EditText(AddInvEst.this);
        makingAmount.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 0.5f));
        makingAmount.setGravity(Gravity.CENTER);
        makingAmount.addTextChangedListener(makingAmountTextWatcher);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!