Archive for August, 2009

Building mix-up custom Android component/widget using Java class and XML layout

August 27, 2009

A lot of times you would find it convenient to just create “compound components” or what Commons guy called “meta” widgets.These widgets are compositions of other widgets. Most of the work involved would be to layout those compound components, bind data and wire up controls. For the layout part, it’s convenient to just use mixture of a Java class and a corresponding xml layout file, as opposed to using a pure Java class. Here is how:

1. Create the Java class. It usually extends a Layout class such as a LinearLayout or a RelativeLayout.  You have to define a constructor in the flavor of

public MyHomeBrewedComp(Context context, AttributeSet attr)

If you just use "public MyHomeBrewedComp(Context context)“,  you would get an “java.lang.NoSuchMethodException" error from Console and a “android.view.InflateException: Binary XML file line #nnn: Error inflating class" from CatLog at runtime.

2. Create the corresponding xml layout file under the package “res/layout” folder.  This is the xml version of your Java class, which means the root node should be the identical class to your Java class.

3. Layout compound widgets in your enclosing widget. If you are doing layout in the xml file, you will then have to inflate the xml in your java file programmatically. You do this by overriding the widget’s onFinishInflate () method.

protected void onFinishInflate(){
((Activity)getContext()).getLayoutInflater().inflate(R.layout.myhomebrewedComp, this);
//other code comes here, such as wiring up controls

4. TODO: setting up attributes in the custom widget

5.  Using the widget in XML.  First of all you will need a new namespace when you refer to any property/attribute in your widget; second you have to use the full-qualified class name in the xml file. Here is a sample:

<?xml version=”1.0″ encoding=”utf-8″?>

app: friction=”.7f”


Synchronizing small projects in eclipse

August 17, 2009
  • To export the project as a zip: File>General>Archive File;
  • To import it back to the workspace: File>General>Existing Projects into Workspace
    and select the aforementioned zip file. This will result in a new folder in the root of the current workspace.