Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

CalculationTextView in Android

CalculationTextView in Android


import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class CalculationTextView extends TextView {

    public CalculationTextView(Context context) {
        super(context);
    }

    public CalculationTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CalculationTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
        try {
            String[] numbers = text.toString().split("[+\\-*/]");
            double result = Double.parseDouble(numbers[0]);
            for (int i = 1; i < numbers.length; i++) {
                String operator = text.toString().substring(
                        text.toString().indexOf(numbers[i]) - 1,
                        text.toString().indexOf(numbers[i]));
                double value = Double.parseDouble(numbers[i]);
                switch (operator) {
                    case "+":
                        result += value;
                        break;
                    case "-":
                        result -= value;
                        break;
                    case "*":
                        result *= value;
                        break;
                    case "/":
                        result /= value;
                        break;
                }
            }
            super.setText(String.valueOf(result), type);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
            // ignore exception and display the original text
        }
    }
}

        

Post a Comment