简体   繁体   中英

Calculate and Show Result in TextView- Android Studio, Java

I am new to Java /android studio, need help with this-

I have a TextinputEditText field- accountEt (one can input number to this field)

I need to calculate and display- accountEt * ((100-3) / 100); [Basically, if 100 entered it shows 97, if 10 entered it shows 9.7]

How to do this in android studio? > show the result (9.7) in a TextView properly.

Like-

Textfield accountEt- [10] | (edit text)
Result- [9.7] |(text view)

Any help is useful.

  1. Get edit Text value in String.
  2. calculate the result and store in the String Data Type.
  3. Show on String value on the Text View.

    String calculate=accountEt.getText.ToString();

    String newCalcualatedValue=calculate.toInt* ((100-3) / 100);

    textView.setText(newCalcualatedValue);

If you use a button to calculate the result. In your button onclick listener just save the value of text value to string and calculate the resut using the value and store it another variable. And finally set the result to your edittext

int a=Integer.parseInt(edittextname.gettext().tostring()); float result=a * ((100-3) / 100); accountet.settext(Float.toString(result));

If you want to update the text automatically on text input, do this:

accountEt.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

       // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        // TODO Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {

        String text = editText.getText().toString();
        int num;
        if (text.isEmpty())
            num = 0;
        else
            num = Integer.parseInt(editText.getText().toString());
        double res = num * 0.97;
        result.setText(Double.toString(res));
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM