简体   繁体   中英

Display automatically an Integer value from Edit Text (entered by the user) to Text View without any actions?

I want to complete a project in which the user writes different characters like A, D, C in an edit text box and then automatically the values of those characters are collected (Addition in each other) in another text box. For example if user pressed A then its value to textbox 10 and then user pressed B, its value 20 to textbox with A+B value. I am using the given code but not getting success.

your text
saif1.addTextChangedListener(new TextWatcher() { @SuppressLint("SetTextI18n") @Override public void afterTextChanged(Editable mEdit) { String text = mEdit.toString();

            if (text.equals("A")) {

                    charactervalue.setText("10");
                    
                String n1 = charactervalue.getText().toString();
                int n11 = Integer.parseInt(n1);
                String n2 = result.getText().toString();
                int n22 = Integer.parseInt(n2);
                finaltotal.setText(String.valueOf(n11 + n22));

            }else if(text.equals("B")) {

                charactervalue.setText("20");

            }

        }

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

        }

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

        }

    });

Try this Code

binding.saif1.addTextChangedListener(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 mEdit) {
        String text = mEdit.toString();
        int temp = 0;

        for (char ch : text.toCharArray()) {
            if (ch == 'A') {
                temp += 10;
            } else if (ch == 'B') {
                temp += 20;
            }
        }

        binding.textView.setText(String.valueOf(temp));
    }
});

You can add more condition by duplicating else if case.. eg

else if (ch == 'C') {
    temp += 30;
}

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