Android Button
Android Button represent a push-button. The
android.widget.Button is subclass of TextView class and CompoundButton is the
subclass of Button class.
There are different types of buttons in android such
as RadioButton, ToggleButton, CompoundButton etc.
Here,we are goig to create two textfield and one button for
sum of two numbers. If user clicks button, sum of two input values is displayed
on the Toast.
Now write the code to generate the UI components
File:activity_main
<?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">
<EditText
android:id="@+id/number1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter First
number"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"/>
<EditText
android:id="@+id/number2"
android:layout_below="@+id/number1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter Second
number"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:onClick="addition"
android:layout_marginTop="15dp"
android:layout_below="@+id/number2"/>
</RelativeLayout>
Activity class
Now write
the code to display the sum of two numbers.
File:MainActivity.java
import
android.support.v7.app.AppCompatActivity;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.View;
import
android.widget.Button;
import
android.widget.EditText;
import
android.widget.Toast;
public
class MainActivity extends AppCompatActivity {
Button b1;
EditText et1,et2;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1= (EditText)
findViewById(R.id.number1);
et2= (EditText)
findViewById(R.id.number2);
b1= (Button) findViewById(R.id.button);
}
public void addition(View view) {
String n1=et1.getText().toString();
String n2=et2.getText().toString();
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int sum=a+b;
Toast.makeText(this,
String.valueOf(sum), Toast.LENGTH_SHORT).show();
}
}
Output: