Monday, November 24, 2008

Adding touch support

No List implementation is complete without support for touch screen.
Since MIDP 1.0 Canvas has support for touch screen devices with pointer methods.
To make things easier we add an int attribute to hold the top pixel from where items are painted.
Every time an item is added or removed this attribute is changed.
Below are the changes on the code from previous post:


public class CustomImplicitList extends Canvas {
private int baseY;

public CustomImplicitList(String title) {
// ...
this.baseY = (title == null) ? this.getHeight() : this.getHeight() - font.getHeight();
this.baseY >>= 1;
}

public void insert(int index, String item) {
// ...
if (font.getSize() != Font.SIZE_SMALL && this.font.stringWidth(item) >= getWidth()) {
this.baseY = (title == null) ? this.getHeight() : this.getHeight() - font.getHeight();
this.baseY >>= 1;
} else {
this.baseY -= (font.getHeight() / 2);
}
}

public void delete(int index) {
// ...
this.baseY += (font.getHeight() / 2);
}

protected void paint(Graphics g) {
// ...
int y = this.baseY;
}

protected void pointerPressed(int x, int y) {
if (y >= this.baseY) {
int index = (y - this.baseY) / this.font.getHeight();

if (index < this.items.length) {
this.selectedIndex = index;
this.repaint();
}
}
}

protected void pointerReleased(int x, int y) {
if (y >= this.baseY) {
int index = (y - this.baseY) / this.font.getHeight();

if (index == this.selectedIndex) {
this.commandListener.commandAction(SELECT_COMMAND, this);
}
}
}

}

No comments: