Create Some Buttons and a Clock in Android, Page 2
Create Some Buttons in Android
Obviously, we still have some way to go before your app is ready for the Android Market! But let's start by adding a basic button. Adding a button that says Ok is simply a matter of adding a code snippet to themain.xml folder:
The XML code should now look like this:
Check this in the Android Emulator.
Tip: To change the text displayed on the button, you simply need to edit one line:
So, if you wanted your button to say Cancel you would enter:
With Android, the buttons you can add are practically endless, but another popular button is the radio button. Again, thanks to Eclipse and the ADT project, this is simply a matter of writing a few lines of code:
The entire code should now look like this:
Run this code in the Android Emulator and you will see a radio button has successfully been added.
Tip: Again, changing the text displayed on this button is simply a matter of altering one line:
Creating a Clock Widget in Android
Now you've got the hang of creating some buttons, it's time to try something more complicated.
In themain.xml file, delete the code for the two buttons you have just created (or alternatively, create a new Android project). In this part of the tutorial, we're going to create an analog clock and then move it around the screen.
The XML for a basic analog clock is:
Add this to your existing code:
Check this is the Android Emulator. You should now see a working analog clock!
Your clock will automatically appear in the top left hand corner, but we can change this by adding a few lines of code and specifying whether the clock should appear centered, in the right hand corner, or at the bottom of the screen. The code you should add/modify, has been highlighted in the screenshot below:
Run this in the Android Emulator.
Changing the location of the clock is a similar process to altering the text for your buttons; simply modify the following line:
For example, if you wanted your clock to be displayed in the right hand corner, the command would be:
If you've caught the Android bug and want to learn more about developing for this increasingly popular platform, Lars Vogel has published one of the most comprehensive tutorials on the Web.
Originally published on http://www.developer.com.
Page 2 of 2