简介ViewGroup

ViewGroup是一种特别的View,它可以作为一个视图组件的容器,从而在里面添加其他的视图组件。这是它的相关继承关系:

从这图片中,我们就不会感到陌生了。


继承GroupView时,onLayout()是必须重写的。

其中很重要的三个方法是:onMeasure(),onLayout(),ondispatchDraw()。

他们分别执行组件的测量,位置和绘制,执行顺序:

子组件的个数不为0,当添加子组件的时候会引起容器的状态发生变化。从而子组件的大小和位置就需要重新测量,所以会调用多次。


下面我们做个小实例:

public class MyViewGroup extends ViewGroup {

	public MyViewGroup(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public MyViewGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public MyViewGroup(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		// ImageView mButton = new ImageView(context);
		// mButton.setBackgroundColor(Color.GREEN);
		// addView(mButton);
	}

	/**
	 * 设置组件的大小
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// 获取该ViewGroup的实际长和宽 涉及到MeasureSpec类的使用
		int specSize_Widht = MeasureSpec.getSize(widthMeasureSpec);
		int specSize_Heigth = MeasureSpec.getSize(heightMeasureSpec);
		// 设置本ViewGroup的宽高
		setMeasuredDimension(specSize_Widht, specSize_Heigth);
	}

	/**
	 * 设置组件的位置
	 */
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// TODO Auto-generated method stub
		View view = null;
		// 获取在onMeasure中计算的视图尺寸
		int lastTop = 0;
		int height = 10;
		// l:左边距 t:上边距 r:与左边距的差值为宽 b:与上边距的差值为高(默认分别为满屏 ,为: 0:0:480:724)
		for (int index = 0; index < getChildCount(); index++) {
			view = getChildAt(index);
			lastTop += index * 50;
			// 所以 高度就50(lastTop+50 -lastTop)
			view.layout(l, lastTop, r, lastTop + 50);
		}
	}

	/**
	 * 绘制组件
	 */
	@Override
	protected void dispatchDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.dispatchDraw(canvas);
	}
}

活动界面添加两个ImageView:

@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		MyViewGroup group = new MyViewGroup(this);
		group.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));

		ImageView imgA = new ImageView(this);
		imgA.setBackgroundColor(Color.CYAN);
		group.addView(imgA);

		ImageView imgB = new ImageView(this);
		imgB.setBackgroundColor(Color.BLUE);
		group.addView(imgB);

		setContentView(group);
	}

结果:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值