Sunday, March 21, 2010

How to make a simple ListView

I have been frustrated about the fact that all of the handy adapter classes used with ListView take a resource id for the view to be used to present list items. When scripting Android, you typically do not create the layout using XML, rather you create widgets programatically. Why not put in a constructor that accepts a view factory rather than a resource id? (Note that it is perfectly possible to create a DSL for defining user interfaces in a declarative way in JavaScript, to replace XML definitions. By the way, anyone knows if there is a way to dynamically manipulate and update XML definitions on the device?).

Now, while experimenting with creating a custom ListAdapter in JavaScript, I discovered that there are predefined resources that can be used to specify the type of list view item. Very handy! (Still miss a constructor that accepts a view factory!)

Here is an example of how to create a sample application that displays a simple list view. Start the server in the DroidScript app, go to http://droidscript.se and enter the ip-address of the device, then paste the function below into the editor, select it, and click "Run as Activity", which will run the selected code as a new activity.
function onCreate(bundle)
{
    var lang = Packages.java.lang;
    var android = Packages.android;
    var widget = Packages.android.widget;

    var listView = new widget.ListView(Activity);

    var fruits = lang.reflect.Array.newInstance(lang.String, 3);
    fruits[0] = "Lemon";
    fruits[1] = "Peach";
    fruits[2] = "Plum";

    var arrayAdapter =
        new widget.ArrayAdapter(Activity,
           android.R.layout.simple_list_item_1,
           fruits);

    listView.setAdapter(arrayAdapter);

    Activity.setContentView(listView);
}

0 comments:

Post a Comment