How to Add Two No in Android

In my last example we have discussed about the textview and button. Text view to display any text. In this example we are going to create an app to add two numbers.

Create an android project and use following Text Fields control to take input from the user.

I have taken two textview to display message and one textview to display output. Two plan text field i.e EditText to take input and one button.

Design Code

		
		<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter First Number:-"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/textView" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Second Number"
    android:id="@+id/textView2"
    android:layout_below="@+id/editText"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText2"
    android:layout_below="@+id/editText"
    android:layout_toRightOf="@+id/editText"
    android:layout_toEndOf="@+id/editText" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sum of Two No"
    android:id="@+id/button"
    android:layout_below="@+id/editText2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tv_result"
    android:layout_below="@+id/button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

		

This screen will display like:-


		
		android design page for two sum
		Figure 1
		


Now add a click event to button. Suppose I have created sum method in java file and map this event to click




		
		Public void sum(View v)
{
    
    
    
}


		set click event
		Figure 2
		

Now use the following code to sum of these two EditText.




		
	public void sum(View v)
 {

     //get the edit text
     EditText t1=(EditText)findViewById(R.id.editText);
     EditText t2=(EditText)findViewById(R.id.editText2);

     //convert value into int
     int x=Integer.parseInt(t1.getText().toString());
     int y=Integer.parseInt(t2.getText().toString());

     //sum these two numbers
     int z=x+y;

     //display this text to TextView
     TextView tv_data=(TextView)findViewById(R.id.tv_result);
     tv_data.setText("The sum is "+z);
     
 }


		


Now execute the code and you will get following output:-


		
		android output
		Figure 3