Corey
Corey

Reputation: 35

Android add and divide at the same time

You only enter one integer or decimal in the TextView.

Let's say you enter 5 and click enter it should do the calculations and display the result.

I'm new to Java and Android. I'm new to Java and Android. I'm new to Java and Android. I'm new to Java and Android.

Upvotes: 1

Views: 99

Answers (1)

aneurinc
aneurinc

Reputation: 1238

TextView is read only - use EditText instead.

  1. Set EditText to digits only:

    android:inputType="numberDecimal"
    
  2. Set onKeyListener to listen for "Enter" press and call calculation:

    editText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && 
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {
    
                    // Perform your calculation on key press and update edit text
                    editText.setText(String.valueOf(doCalc(
                        Double.valueOf(editText.getText().toString())));
    
                    return true;
                }
                return false;
            }
        });   
    
  3. Create method for calculation:

    private double doCalc(double average_bg) {
        return (2.59 + average_bg) / 1.59;
    }
    

Upvotes: 4

Related Questions