最近,有项目中用LWUIT做UI时,发现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++;
}
}
}