Cómo agregar funcionalidad +/- a un butting en Android kotlin

Necesito agregar un nuevo button con funcionalidad de +/-. Si el usuario hace clic en el button por primera vez, el valor debería regresar -> "-" (ex => -123), si el usuario vuelve a hacer clic en el valor "-" debe eliminarse (ex => 123). La funcionalidad es similar al button +/- en la calculadora.

Aquí está mi código

Archivo Activity.kt

package com.tripbegins.calculator import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import com.tripbegins.calculator.R.id.* import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } var emptyText = true fun numberEvents(view: View) { var checkButton:Boolean = false if(emptyText){ viewResult.setText("") } emptyText = false var button = view as Button var isClicked = viewResult.text.toString() when (button.id) { buttonOne.id -> isClicked += "1" buttonTwo.id -> isClicked += "2" buttonThree.id -> isClicked += "3" dotButton.id-> isClicked+="." } viewResult.setText(isClicked) } var operation ="+" var oldValues:String? = null fun mathOperation(view: View){ var mathButton = view as Button var isClicked = viewResult.text.toString() when(mathButton.id){ plusButton.id-> { operation = "+" } minusButton.id->{ operation="-" } mulButton.id->{ operation="*" } } oldValues = viewResult.text.toString() emptyText = true } fun Calculate(view: View){ var newValues = viewResult.text.toString() var calulateButton:Double? = null when(operation){ "+"-> { calulateButton = oldValues!!.toDouble() + newValues.toDouble() } "-"-> { calulateButton = oldValues!!.toDouble() - newValues.toDouble() } "*"-> { calulateButton = oldValues!!.toDouble() * newValues.toDouble() } } viewResult.setText(calulateButton.toString()) emptyText=true } fun clearFunction(view: View){ viewResult.setText("") } } 

file activity.xml

 <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.tripbegins.calculator.MainActivity"> <EditText android:id="@+id/viewResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="42dp" android:ems="10" android:gravity="bottom|right" android:inputType="textPersonName" android:text="0" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/buttonTwo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="76dp" android:onClick="numberEvents" android:text="2" app:layout_constraintStart_toEndOf="@+id/buttonOne" app:layout_constraintTop_toBottomOf="@+id/viewResult" /> <Button android:id="@+id/plusButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="38dp" android:onClick="mathOperation" android:text="+" app:layout_constraintBaseline_toBaselineOf="@+id/minusButton" app:layout_constraintStart_toStartOf="parent" /> <Button android:id="@+id/minusButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:layout_marginTop="33dp" android:onClick="mathOperation" android:text="-" app:layout_constraintStart_toEndOf="@+id/plusButton" app:layout_constraintTop_toBottomOf="@+id/buttonTwo" /> <Button android:id="@+id/mulButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="26dp" android:onClick="mathOperation" android:text="*" app:layout_constraintBaseline_toBaselineOf="@+id/minusButton" app:layout_constraintStart_toEndOf="@+id/minusButton" /> <Button android:id="@+id/calButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="44dp" android:onClick="Calculate" android:text="Calculate" app:layout_constraintStart_toStartOf="@+id/minusButton" app:layout_constraintTop_toBottomOf="@+id/minusButton" /> <Button android:id="@+id/buttonThree" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="26dp" android:onClick="numberEvents" android:text="3" app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo" app:layout_constraintStart_toEndOf="@+id/buttonTwo" /> <Button android:id="@+id/buttonOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="34dp" android:onClick="numberEvents" android:text="1" app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo" app:layout_constraintStart_toStartOf="parent" /> <Button android:id="@+id/dotButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="22dp" android:onClick="numberEvents" android:text="." app:layout_constraintBaseline_toBaselineOf="@+id/calButton" app:layout_constraintEnd_toStartOf="@+id/calButton" /> <Button android:id="@+id/clearButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="11dp" android:onClick="clearFunction" android:text="Clear" app:layout_constraintBaseline_toBaselineOf="@+id/calButton" app:layout_constraintStart_toEndOf="@+id/calButton" /> </android.support.constraint.ConstraintLayout> 

Archivo actualizado Activity.kt He actualizado el código para = = -. Se agregó la var fuera de la function

  var emptyText = true var isMinusPrinted=false fun numberEvents(view: View) **Current result** If button clicked for the first time value => -123 If button clicked for the second time value => -123 If button clicked for the third time value => --123 **Expected Result** If button clicked for the first time value => -123 If button clicked for the second time value => 123 If button clicked for the third time value => -123 

Archivo actualizado activity.kt

 package com.tripbegins.calculator import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import com.tripbegins.calculator.R.id.* import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_main.view.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } var emptyText = true var isMinusPrinted=false fun numberEvents(view: View) { if(emptyText){ viewResult.setText("") } emptyText = false var button = view as Button var plusMinusCheck ="" var isClicked = viewResult.text.toString() when (button.id) { buttonOne.id -> isClicked += "1" buttonTwo.id -> isClicked += "2" buttonThree.id -> isClicked += "3" dotButton.id -> { isClicked += "." dotButton.isClickable = false //**add this line here** } plusMinusBtn.id->{ var resultWithoutMinus=isClicked//ex: 123 if(!isMinusPrinted){ isClicked = "-" + resultWithoutMinus//this line for example give result like: -123 isMinusPrinted=true } else{ isClicked=resultWithoutMinus //result became : 123 isMinusPrinted=false } } } viewResult.setText(isClicked) } var operation ="+" var oldValues:String? = null fun mathOperation(view: View){ var mathButton = view as Button var isClicked = viewResult.text.toString() when(mathButton.id){ plusButton.id-> { operation = "+" } minusButton.id->{ operation="-" } mulButton.id->{ operation="*" } } oldValues = viewResult.text.toString() emptyText = true dotButton.isClickable=true//**add this line here** } fun Calculate(view: View){ var newValues = viewResult.text.toString() var calulateButton:Double? = null when(operation){ "+"-> { calulateButton = oldValues!!.toDouble() + newValues.toDouble() } "-"-> { calulateButton = oldValues!!.toDouble() - newValues.toDouble() } "*"-> { calulateButton = oldValues!!.toDouble() * newValues.toDouble() } } viewResult.setText(calulateButton.toString()) emptyText=true dotButton.isClickable=true //**add this line here** } fun clearFunction(view: View){ viewResult.setText("") dotButton.isClickable=true //**add this line here** } } 

Se actualizó el file xml para el button -> +/-

 <Button android:id="@+id/plusMinusBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="52dp" android:layout_marginStart="38dp" android:onClick="numberEvents" android:text="+/-" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" /> 

Editar :

  var emptyText = true var isMinusPrinted=false//add this line here fun numberEvents(view: View) { var checkButton:Boolean = false if(emptyText){ viewResult.setText("") } emptyText = false var button = view as Button var isClicked = viewResult.text.toString() when (button.id) { buttonOne.id -> isClicked += "1" buttonTwo.id -> isClicked += "2" buttonThree.id -> isClicked += "3" dotButton.id-> isClicked+="." plusMinusBtn.id->{//add this block of code from here var resultWithoutMinus=Math.abs(isClicked.toInt()) //ex: 123 if(!isMinusPrinted){ isClicked = "-" + resultWithoutMinus//this line for example give result like: -123 isMinusPrinted=true } else{ isClicked=resultWithoutMinus //result became : 123 isMinusPrinted=false } }//to here } viewResult.setText(isClicked) } 
  • En Kotlin Lenguaje de progtwigción importancia de varargs en términos de usos
  • ¿Cómo hacer AppBar universal con Anko DSL?
  • Clase Kotlin no encontrada
  • Kotlin - Lista dentro de un filter de list
  • Dagger2 inyecta un presentador en un error de actividad de Kotlin
  • Cambiar el filter de color del elemento del cajón de navigation también cambia el imageView, que es el mismo ID de image
  • Kotlin: No se puede encontrar la class de símbolo Fragmento u otras classs de Android
  • Comprobación de conectividad no funciona en Android Oreo Kotlin
  • Obligatorio <Objeto> y encontrado <Objeto>?
  • Los cambios de Android Studio 3.0 Kotlin no se reflejan en la compilation
  • No se pueden agregar las extensiones de Kotlin para Android a mi proyecto