This example demonstrates I’ll show you how to add two EditText values in Android using Java.
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.java
You may also like: Android Alert Dialog Example
Java
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 | import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText editNum1,editNum2; TextView textResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void addNumbers(View view){ editNum1= findViewById(R.id.editNum1); editNum2= findViewById(R.id.editNum2); textResult= findViewById(R.id.textResult); double num1 = Double.parseDouble(editNum1.getText().toString()); double num2 = Double.parseDouble(editNum2.getText().toString()); double result = num1 + num2; textResult.setText(Double.toString(result)); } } |
Output:
![Android Add Two Numbers using Java and Kotlin](https://i0.wp.com/www.code4example.com/wp-content/uploads/2022/05/image-46.png?resize=429%2C860&ssl=1)