J2ME GUI实战之9 ----------自定义控件布局,DIY Layout

针对LWUIT中GridLayout存在的问题,本文介绍了一种新的布局方式。通过自定义布局算法,实现了控件间的自适应排列,特别是解决了Label控件占用过多空间的问题。此布局能够根据界面大小动态调整控件的位置和尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近,有项目中用LWUIT做UI时,发现GridLayout有个不好的地方,那就是。。。。。如下图:

GridLayout并行显示控件的效果图 可以发现,使用GridLayout是把控件按照界面长宽平分而排列的,左边的Label控件就占了冗余的地方。。。。。。。。。或许你会想到使用其他GridLayout来实现自适应的控件 并排效果,但是LWUIT原有的Layout是没有完全符合这个要求的,所以就只能靠自己DIY一个了。

以下,就是我按照原有GridLayout修改得来的新布局,如下图:

自适应控件布局

直接贴出修改的代码,其中的代码很大一部分是源自GridLayout.java(modify from GridLayout.java),因此只把关键部分贴出来:

public void layoutContainer(Container parent) { int width = parent.getLayoutWidth() - parent.getSideGap() - parent.getStyle().getPadding(Component.RIGHT) - parent.getStyle().getPadding(Component.LEFT); int height = parent.getLayoutHeight() - parent.getBottomGap() - parent.getStyle().getPadding(Component.BOTTOM) - parent.getStyle().getPadding(Component.TOP); int x = parent.getStyle().getPadding(Component.LEFT); int y = parent.getStyle().getPadding(Component.TOP); int numOfcomponents = parent.getComponentCount(); //取得所有Label控件的最长字符串 String str=""; for(int i=0;i<numOfcomponents;i+=2)//Label控件处于0,2,4,6....... { String tmpstr=((Label)(parent.getComponentAt(i))).getText(); if(tmpstr.length()>str.length()) str=tmpstr; } //Label控件的长度 int lbWidth=((Label)(parent.getComponentAt(0))).getStyle().getFont().stringWidth(str); lbWidth*=1.3; //与Label并行的控件的长度 int cmpWidth = width-lbWidth; int cmpHeight; if (numOfcomponents > rows * columns) { cmpHeight = (height)/(numOfcomponents/columns +1);//actual rows number } else { cmpHeight = (height)/rows; } int row = 0; for(int i=0; i< numOfcomponents; i++){ Component allCmp = parent.getComponentAt(i); Style cmpStyle = allCmp.getStyle(); int marginLeft = cmpStyle.getMargin(Component.LEFT); int marginTop = cmpStyle.getMargin(Component.TOP); int marginRight = cmpStyle.getMargin(Component.RIGHT); int marginBottom= cmpStyle.getMargin(Component.BOTTOM); if(i%2==0){//如果是Label控件,偶数 allCmp.setWidth(lbWidth - marginLeft - marginRight); allCmp.setX(x + marginLeft); } else{//如果是与Label控件并行的控件,奇数 allCmp.setWidth(cmpWidth - marginLeft - marginRight); allCmp.setX(x + lbWidth + marginLeft); } allCmp.setHeight(cmpHeight - marginTop - marginBottom); allCmp.setY(y + row*cmpHeight + marginTop); if((i + 1)%columns == 0){ row++; } } }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值