简体   繁体   English

在 TextView 中计算并显示结果 - Android Studio、Java

[英]Calculate and Show Result in TextView- Android Studio, Java

I am new to Java /android studio, need help with this-我是 Java /android 工作室的新手,需要帮助 -

I have a TextinputEditText field- accountEt (one can input number to this field)我有一个 TextinputEditText 字段-accountEt(可以在该字段中输入数字)

I need to calculate and display- accountEt * ((100-3) / 100);我需要计算并显示-accountEt * ((100-3) / 100); [Basically, if 100 entered it shows 97, if 10 entered it shows 9.7] [基本上,如果输入 100 则显示 97,如果输入 10 则显示 9.7]

How to do this in android studio?如何在 android 工作室中做到这一点? > show the result (9.7) in a TextView properly. > 在 TextView 中正确显示结果 (9.7)。

Like-喜欢-

Textfield accountEt- [10] |文本字段 accountEt- [10] | (edit text) (编辑文本)
Result- [9.7] |(text view)结果- [9.7] |(文本视图)

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();字符串计算=accountEt.getText.ToString();

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

    textView.setText(newCalcualatedValue); 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.在您的按钮 onclick 侦听器中,只需将文本值的值保存到字符串并使用该值计算结果并将其存储为另一个变量。 And finally set the result to your edittext最后将结果设置为您的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));
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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