In this post, I will show you how to create a Button in Android Studio.
Button Example for Android Studio
A button is a very basic UI in Android studio that is used in almost all types of android apps. On clicking the button we can perform any desired task. A button consists of text or an icon. There are also Image buttons which function almost the same,only they will display an image which is clickable and you can perform any task once the button is clicked.
Inserting the Button in your layout
A button can be created in XML (activity_main.xml) layout by using the <button> tag as shown below:-
android:text="I am A Button"/>
Adding Function for Button Clicks
The OnClickListener is a function which is used to capture the event of clicking on a button and performing the desired task after the button is being clicked. To create this event handler, first create a View.OnClickListener object and then assign it to the Button by calling the setOnClickListener function. The corresponding function code for MainActivity.java file is shown below:-
Toast.makeText(getApplicationContext(),"Thanks for clicking ",Toast.LENGTH_SHORT).show();
The above code will create a variable of type Button with name btn and then call the OnClickListener to capture the event of that button being clicked. Once the event is captured,it will show a Toast on the screen, with the message “Thanks For Clicking”, once the user clicks on the button.
A button is shown below for example purpose that will print the message “Thanks for clicking” once clicked:-
The Full Java Code along with the XML layout for the above example is shown below:-
You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project. You can also try to play with these layout settings on your own and see the corresponding changes accordingly. There are a variety of properties available which can be changed to make your button more materialized and fancy looking.
For a more detailed guide, you can also visit android’s official guide below:-