前段时间一直为九宫格烦恼,项目又希望使用高级界面,但是九宫格这样的东东实现是想不到好的办法,好像没有合适的控件可以完成这个任务。后来终于想起了万能的CustomItem,用他来搞定九宫格。本例就是使用CustomItem 来实现了一个九宫格效果,效果如下图:

MyIem.java(实现九宫格Item)代码如下:
package src; import javax.microedition.lcdui.*; public class MyItem extends CustomItem { private Image image; private String title; private int height; private int width; public MyItem(Image image, String title,int width,int height) { super(null); this.image = image; this.title = title; this.height = height; this.width = width; } public int getMinContentHeight() { return this.height; } public int getMinContentWidth() { return this.width; } public int getPrefContentHeight(int width) { return getMinContentHeight(); } public int getPrefContentWidth(int height) { return getMinContentWidth(); } public void paint(Graphics g, int w, int h) { g.drawImage(this.image, w/2, 0, Graphics.HCENTER | Graphics.TOP); g.setColor(0x333333); g.drawString(this.title, w/2, h - g.getFont().getHeight(), Graphics.HCENTER | Graphics.TOP); } public void keyPressed(int keyCode) { if(keyCode == -5){ System.out.println(this.title + " is pressed!"); } } }
调度form代码片段
Form f = new Form("CustomItem"); int tempWidth = f.getWidth() / 4; int tempHeight = 60; for(int i = 0; i < 9;i++) { String imgSrc = "/img/" + i + ".png"; try { Image img = Image.createImage(imgSrc); MyItem mi = new MyItem(img,String.valueOf(i) + " item",tempWidth,tempHeight); mi.setLayout( Item.LAYOUT_CENTER );//居中 f.append( mi ); } catch(IOException ioe) { ioe.printStackTrace(); } } display.setCurrent( f );
这样一个九宫格就做完了,要现实相应的动作和更丰富的效果可以根据CustomItem以及Item的接口进行丰富。
本文介绍了一种使用CustomItem创建九宫格界面的方法,通过自定义控件MyItem实现了图片和文字的统一布局,并展示了完整的代码示例。
3888

被折叠的 条评论
为什么被折叠?



