This example demonstrates I’ll show you how to add two EditText values in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp"> <TextView android:id="@+id/textResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="Code4Example" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <EditText android:id="@+id/editNum1" android:inputType="number" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" /> <EditText android:id="@+id/editNum2" android:inputType="number" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/editNum1" android:layout_centerInParent="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editNum2" android:layout_centerInParent="true" android:onClick="addNumbers" android:text="Add Numbers" /> </RelativeLayout> |
Step 3 − Add the following code to src/MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var editNum1:EditText lateinit var editNum2:EditText lateinit var textResult: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "Code4Example.Com" } fun addNumbers(view: View?) { editNum1 = findViewById(R.id.editNum1) editNum2 = findViewById(R.id.editNum2) textResult = findViewById(R.id.textResult) val num1 = editNum1.text.toString().toDouble() val num2 = editNum2.text.toString().toDouble() val result = num1 + num2 textResult.text = java.lang.Double.toString(result) } } |
Output: