how to change text in a TextView dynamically based

2019-08-01 00:05发布

问题:

Good morning everyone. I know from the title it's everything confused, so I will try to explain it better. I need to create an app for a medical project to calc HbA1c. I have 3 editText in which I type values of medical test. Each of three changes because of other one. For example: if I have 42 in one, the other one is 5.99%. And so on. I'm trying to make them change dynamically: change still during I'm writing. I tried using an OnCliclListener but I have to write the entire value.

I don't know if I explain myself as good to make you understand.

Thank you very much

回答1:

Instead of using onClickListener, try using addTextChangedListener() and change your TextViews whenever onTextChanged() is called. By using this you can even change them while typing.

It looks something like this:

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence c, int i, int i2, int i3) {
            }

            @Override
            public void onTextChanged(CharSequence c, int i, int i2, int i3) {
                if (c.length() > 0) {
                } else {
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });


回答2:

Though answer by @Anjani is correct and you could use it but I would recommend using Butterknife. Here is the code:

@OnTextChanged(value = R.id.editText,
        callback = OnTextChanged.Callback.TEXT_CHANGED)
void afterCommentTextChange(CharSequence s, int start, int before, int count) {
  // Do what ever you want here when text is changed
}