Ad

How To Get Input From User In Android Studio In Numeric Value And Convert It Into Variable Int In Kotlin?

- 1 answer

Hello everyone I am trying to make Calculator in Android Studio , As I am new Kotlin and Java therefore it is difficult for me.

Here is the source code of mine mainActivity xml file :

    <EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName|number"
    app:layout_constraintBottom_toTopOf="@+id/editText2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.094"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.753"
    tools:hint="First Number"
    android:numeric="integer|decimal"/>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="none|textPersonName|number"
    app:layout_constraintBottom_toTopOf="@+id/editText3"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.094"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/editText1"
    tools:hint="Second Number"
    android:numeric="integer|decimal"/>

<TextView
    android:id="@+id/editText3"
    android:layout_width="217dp"
    android:layout_height="36dp"
    android:text="Answer"
    app:layout_constraintBottom_toTopOf="@+id/okactivity2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.095"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/editText2" />

And here is my Android mainActivity.kt file

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)

    okactivity2.setOnClickListener{
        val num1 = editText1.text
        val user1: Int = num1
        val num2 = editText2.text
        val user2: Int = num2
         val sum = user1 + user2
        editText3.setText("Answer is $sum")

    }

}

Here i am unable to convert string editText1 and editText2 into an int , so that i can set ediText3 As Answer

Ad

Answer

EditText's text property is of type Editable. You'll need to transform it to String first, and then convert it to an Int:

val num1 = editText1.text.toString().toInt()
Ad
source: stackoverflow.com
Ad