So after learning some Android basics using Note Pad tutorial, I decided to write a simple program on my own. Note Pad was a great tutorial, but I always feel that the best way to master a programming language by trials and errors. So, I began to write a simple Hello World program (Yep, hello world again..) which greets according to the name users type in. So, if you type in Paras, it will display "Hello, Paras".
So, for my program, I need a button, a text field input and a text output. I've always been confused about layout for Android. I know that for each layout, you are supposed to write an xml file and put it under /layout folder in the project. The file strings.xml under /values folder hold all the key value pairs. So, for example, if I want to put a button that says "Say Hello", I put button in the .xml file under /layout folder. The button name will have to be specified in strings.xml. I know this is a very confusing way of doing GUI. However, thanks you a blog post I found using Google, I found DroidDraw(
http://www.droiddraw.org/). It's beta version, but it is useful. You can generate layout xml codes using DroidDraw. However, you will still need to modify strings.xml file on your own.
If you have learned a little bit of Java Swing, you will find Android very similar to it. They used same concepts such as Action Events.
Instead of posting the whole code, I'll just state the important ones. When you launched your android application, you will have to do set up and this is done inside onCreate() method. onCreate() methods is from Activity package which has to be extended in every Android application. Each application can have one or more activities. For example, launching the application is one activity and pressing a button can be another activity but doesn't have to be.
Then you can set your layout by writing
setContentView(R.layout.main);
R.layout is the default for all application and main is the name of your layout file. In my case, my layout file is named main.xml.
Next thing is you want to say hello, when user click the button. So, like Swing, Android uses event listeners. We have button objects and event listeners are set to those button objects. We need to get a reference to our button object first. To do this, we say
button = (Button)findViewById(R.id.sayHelloButtonId);
The layout file, main.xml has a button tag and the tag will have an id reference. We're using that id to find our button object. So, the last steps is displaying hello,
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sayHello();
}
});