Android: XML layouts

So, I’ve been fiddling around w/ ADT for a couple of hours now. It’s possible to programmatically create layouts (i.e. an Android UI), but it’s not a great solution. It’s way easier to define the layout in XML, and then bind whatever event handlers are required. Here we have a simple class:

package com.waynekhan;

import android.os.Bundle;
import android.view.*;
import android.widget.*;
import java.util.*;

public class HWA extends Activity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState) {

Button b = (Button) findViewById(;

public void onClick(View v) {
switch (v.getId()) {
case {
Button b = (Button) v;
b.setText(new Date().toString()); break;

As you can see, it’s quite bare. Load an XML layout (R.layout.main), define a button ( and then bind a click listener to said button. Then we have onClick() which simply sets the button text to the current String-ified date. Our code is really clean, and we do all the UI-related stuff in /res/layout/main.xml, and put all our conveniently l10n strings in /res/values/strings.xml. Unfortunately, I can’t post the content of the XML files, since WordPress groks ’em and all I get is an empty code block.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s