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.app.Activity;
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) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.b);
b.setOnClickListener(this);
}

public void onClick(View v) {
switch (v.getId()) {
case R.id.b: {
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 (R.id.b) 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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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