Button Example

Course- Android >

The Android button represents a push-button. The Android.widget.Button TextView is a subclass of the class and the Component Button button is the sub-class of the class.

There are various types of buttons in the radio buttons like Android, Toggleton, Component Button etc.

Here, we are going to create two textfield and one button for the sum of two numbers. If the user clicks, the sum of two input values is displayed on toast

Drag the component or write the code for UI in activity_main.xml

First, drag 2 text fields from the text field palette and one button from the Form Widget Palette is shown in the picture below.android button example

The generated code for the ui components will be like this:

File: activity_main.xml

  
      
      
          
    EditText>  
RelativeLayout>

Activity class

Now write the code to display the sum of two numbers.

File: MainActivity.java

package com.example.sumof2numbers;  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.Toast;  
public class MainActivity extends Activity {  
    private EditText edittext1,edittext2;  
    private Button buttonSum;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        addListenerOnButton();  
    }  
    public void addListenerOnButton(){  
        edittext1=(EditText)findViewById(R.id.editText1);  
        edittext2=(EditText)findViewById(R.id.editText2);  
        buttonSum=(Button)findViewById(R.id.button1);  
        buttonSum.setOnClickListener(new OnClickListener(){  
            @Override  
            public void onClick(View view) {  
                String value1=edittext1.getText().toString();  
                String value2=edittext2.getText().toString();  
                int a=Integer.parseInt(value1);  
                int b=Integer.parseInt(value2);  
                int sum=a+b;  
    Toast.makeText(getApplicationContext(),String.valueOf(sum),Toast.LENGTH_LONG).show();  
            }   
        });  
    }  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.activity_main, menu);  
        return true;  
    }  
}  

It is developed by adt bundle on android 4.2 using minimum sdk 8 and target sdk 16.

Output:

android button example output 1 android button example output 2