Hi everyone!
Having discussed most of the basic concepts required to start the development of Android apps, let’s not wait any more! Let’s go straight to the development!
Today, we will start building the simplest version of the Hello World app (other than the one which is automatically generated! Remember? Refer to Let’s Code!) , in which we will focusing on the use of buttons and toasts(?? Don’t worry! I will discuss!) in Android applications. In the coming few posts, I will be building upon this tutorial to discuss the various concepts finally leading to the development of the app.
So, Let’s start! Open the Hello World Project that we created in the post titled Let’s Begin!.
Go to main.xml in the layout folder, drag a button from Form Widgets and place it onto the WYSIWYG screen. Go to the code! Is there any difference from the code discussed earlier?
Yes! We have a new tag named Button with various attributes! Let’s focus on each of them. Clearly, android:layout_width and layout_height are used to define the width and the height of the button respectively. By default, they are set to wrap_content. I hope you are familiar with this term. If not, please refer to the post titled A look at the code!.
Change the android:layout_width attribute of the Button tag to fill_parent in order to make the button stretched to the entire width of the screen, and leave the android:layout_height as it is. Save main.xml. Your screen in the WYSISYG editor should look as follows:
Refer to the code again. There are two more attributes for the tag Button. The android:text attribute sets the text which is displayed on the button. By default, it is set to Button and that’s why, the default text on the Button widget is Button.
You may also find a warning on this line. Can you guess why is it so? Basically, in the code that is generated automatically, android:text attribute has been set to the string Button whereas as per the correct syntax, one must declare a string variable (for example, button) whose value is Button and then, reference it by using @string/button in the value of this attribute. To fix it, simply click on the attribute, right click and choose Quick Fix. You will be provided with various options. Simply, select Extract String which will display a dialog box, in which set the R.string value to button and String to Button. Click OK and save the file. The text Button will replaced to @string/button and the warning will be gone.
We will look at the android:id attribute later. For now, simply run the project. What do you see?
You will find that there will be a button on the screen but, when you click it, nothing happens! Why?
In the next post, we will discuss the android:id attribute and it’s use in implementing the functioning of a button.
Till then, BYE!
