android studio 组件外边距,Android 扩展-ViewGroup的子View真正实现Margin属性

楼主最近在复习自定义View,在复习到自定义ViewGroup这个知识点时,发现了一个问题--就是我们之前的定义ViewGroup在考虑Margin属性可能有问题。本文在解决该问题给出建议性的意见,但是不一定是正确的,如果有错误或者不当的地方,希望指正。

本文参考文章:

1.Android 手把手教您自定义ViewGroup(一)

2.你的自定义View是否真的支持Margin

1.提出问题

这里我举一个简单的例子来说,假设我们需要定义一个ViewGroup放置一个子View,同时这个子View支持Padding和Margin属性。

这里我先贴出一个常规的写法:

public class CustomViewGroup02 extends ViewGroup {

public CustomViewGroup02(Context context) {

super(context);

}

public CustomViewGroup02(Context context, AttributeSet attrs) {

super(context, attrs);

}

public CustomViewGroup02(Context context, AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

int widthSize = MeasureSpec.getSize(widthMeasureSpec);

int heightSize = MeasureSpec.getSize(heightMeasureSpec);

int widthMode = MeasureSpec.getMode(widthMeasureSpec);

int heightMode = MeasureSpec.getMode(heightMeasureSpec);

//这里假设只有一个子View

measureChildren(widthMeasureSpec, heightMeasureSpec);

View view = getChildAt(0);

MarginLayoutParams lp = (MarginLayoutParams) view.getLayoutParams();

int width = view.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + getPaddingLeft() + getPaddingRight();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值