Home > Software engineering >  Applying auto-calculation to edit text
Applying auto-calculation to edit text

Time:01-27

If the user enters any value like 1234 in the edit text box, then all the values of the edit text box are Addition in each other and the answer is shown in a text box. For example if user enter values such as 1234 in edit text and after addition (1 2 3 4=10) their answer that is 10 show in text box.

CodePudding user response:

You could probably use data binding, either one or two way depending on how you want to do things.

Make sure to read the documentation around data-binding before starting to successfully implement!

Using one-way data binding, you can set a value on an attribute and set a listener that reacts to a change in that attribute - android docs

First set your binding adapters on your new SumNumberTextView, Then in your parent view's layout file, if you want to use the more verbose one way data binding, you'd reference something like:

android:numbers="@{viewmodel.numbers}" and android:onNumbersChanged="@{() => viewmodel.onNumbersChanged()}"

Then you can define a function on your view model that does your numeric operations whenever you input numbers.

CodePudding user response:

You can just use textwatcher on edittext to get update when text change and do your operation of addition just like this

 editText.addTextChangedListener(new TextWatcher() {  
  
            @Override  
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {  
                // call function from here if you want to perform operation as user provide input
                add(cs.toString());
            }  
  
            @Override  
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {  
                Toast.makeText(getApplicationContext(),"before text change",Toast.LENGTH_LONG).show();  
            }  
  
            @Override  
            public void afterTextChanged(Editable arg0) {  
                // call function from here if you want to perform operation only user stop input
                add(arg0.getText().toString());
            }  
        });  


private void add(String input){
    if(input != null && input != ""){
       String[] numbers = input.split("")
       int total = 0;
       for(int counter = 0 ; counter < numbers.length ; counter  ){
          total  = Integer.parseInt(numbers[counter]);
       }
       Log.e("total",total);
    }
}
  • Related