andorid界面布局学习 之 使用代码实现界面布局

 

(1)目的

绘制不等数量的小图标到界面中

(2)效果图

(3)实现介绍

  • 和使用xml布局类似:我们需要有装载控件的容器(ViewGroup)和要显示的控件view
  • 然后在将view添加到viewGroup中,将viewGroup通过Activity的setContentView方法设置到显示界面。
  • 如果通过addView方法将view添加到viewGroup中,则应在viewGroup的onLayout方法中对子控件的位置进行设置
  • 最后提醒一下自己:viewGroup嵌套viewGroup

(4)代码

viewGroup相关实现代码:

View Code
//viewGroup类相关代码
public class MyLayerImageIcon extends ViewGroup{

private int mHeight, mWidth;

public MyLayerImageIcon(Context context, int nHeight, int nWidth) {
super(context);
mHeight = nHeight;
mWidth = nWidth;
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int nCount = getChildCount();
int nTop = 0;
int nBottom = 0;
int nLeft = 0;
int nRight = 0;

for(int i=0; i<nCount; i++){
//自己定义的ImageView控件
ImageIconItem item = (ImageIconItem)getChildAt(i);

nTop = Math.round(item.getmTop());
nBottom = Math.round(item.getmBottom());
nLeft = Math.round(item.getmLeft());
nRight = Math.round(item.getmRight());
//设定控件在viewGroup中的位置
item.layout(nLeft, nTop, nRight, nBottom);
}

}
}

view相关实现代码:

View Code
public class ImageIconItem extends ImageView{

private float mTop, mBottom, mLeft, mRight;

private int mWidth, mHeight;

private Point mPoint;


public ImageIconItem(Context context) {
super(context);
this.setTag(222);
// TODO Auto-generated constructor stub
}

public void setPosition(Point position, int resId){

Resources res = getResources();
     //获得资源图片的大小,也可以直接传进来图片的大小提高效率
BitmapDrawable bitmapDrawable = (BitmapDrawable) res.getDrawable(resId);
Bitmap bmBitmap = bitmapDrawable.getBitmap();
mWidth = bmBitmap.getWidth();
mHeight = bmBitmap.getHeight();
mPoint = position;
//计算图片放置的位置
mTop = position.y - (mHeight/2) ;
mBottom = position.y + (mHeight/2) ;
mLeft = position.x - (mWidth/2) ;
mRight = position.x + (mWidth/2) ;


}



public float getmBottom() {
return mBottom;
}


public float getmTop() {
return mTop;
}


public float getmLeft() {
return mLeft;
}



public float getmRight() {
return mRight;
}


}

主要代码已贴上,欢迎讨论--博客园(junqinghaha)

posted @ 2012-01-11 15:36  junqinghaha  阅读(341)  评论(0编辑  收藏  举报