In this session will learn to create Button.

Create new project in eclipse (Android-First-Programm).

Click on res folder and then layout, now open required xml where you want to use button.


We can create any control like button using both layouts

1) Graphical Layout

2) Xml Layout


1) Using “Graphical Layout” Drag button from “Form Widgets”.


Double click on button and set its properties in xml layout.

2) In Xml Layout write this code to create button.

Now by reference we can use button in code and can use its events.

Open Activity (.java file) to use that button.

Activity is located in src folder -> package and choose activity where you want to use button.


To access button from xml we use its reference using this code.


Using “findViewById();” we can access reference of any control like button from xml layout.

“button1” is id of that button that we want to use and it must be exist in xml layout that we have assigned in “setContentView(R.layout.main);”. So complete code will be


button1 is exists in main layout. We can set reference of layout using “setContentView(R.layout.main);


Button click event:

To set buttons click event use this code.


To check is button is clicked show message using Toast.

Other way to set click event in button is, we can use function name in xml.

And define “button1Click” function in activity, without using button reference.

For your understanding I make two buttons and use button click events by two types.

See complete xml or java files.