function createButton() {
var n = 1;
var Graphics = Packages.android.graphics;
var font = Graphics.Typeface.create(
Graphics.Typeface.SANS_SERIF,
Graphics.Typeface.BOLD);
var button = new Packages.android.widget.Button(Activity);
button.setTypeface(font);
button.setTextSize(26);
button.setBackgroundColor(Graphics.Color.rgb(0, 0, 64));
button.setTextColor(Graphics.Color.rgb(255, 255, 255));
button.setText("How many times can you click me?");
button.setOnClickListener(function () {
button.setText("You clicked me " + n + " times!");
n = n + 1;
});
return button;
}
var layout = new Packages.android.widget.LinearLayout(Activity);
layout.setOrientation(Widget.LinearLayout.VERTICAL);
layout.addView(createButton());
layout.addView(createButton());
layout.addView(createButton());
Activity.setContentView(layout);
Friday, February 26, 2010
An example on the use of closures in JavaScript on Android
Here is a code example that illustrates the use of closures in JavaScript in an Android program. The variable n is introduced in the local scope of the function createButton, and is used in the closure for the button's click listener. Each button will have its own counter value, because each function invocation of createButton allocates its own space for the local variable n.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment