继承ConstraintLayout

开发中复杂的布局基本上都可以通过ConstraintLayout实现,所以我们继承ConstraintLayout实现一个EasyConstraintLayout能够为子view添加圆角和阴影效果。

public class EasyConstraintLayout extends ConstraintLayout {
public EasyConstraintLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public LinearLayout.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}

@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
重写了两个方法,我们要用这些方法实现子view自定义属性的读取,在此之前要在xml中自定义一些属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--为了方便扩展其他layout,定义在外层,命名以layout_开头,否则lint会报红警告-->
<attr name="layout_radius" format="dimension" />
<attr name="layout_shadowColor" format="color" />
<attr name="layout_shadowEvaluation" format="dimension" />
<attr name="layout_shadowDx" format="dimension" />
<attr name="layout_shadowDy" format="dimension" />
<!--用统一一个EasyLayout,用于封装读取自定义属性-->
<declare-styleable name="EasyLayout">
<attr name="layout_radius" />
<attr name="layout_shadowColor" />
<attr name="layout_shadowEvaluation" />
<attr name="layout_shadowDx" />
<attr name="layout_shadowDy" />
</declare-styleable>
<!--和EasyLayout属性列表一样,但是命名要以XXX_Layout格式,这样开发工具会提示自定义属性-->
<declare-styleable name="EasyConstraintLayout_Layout">
<attr name="layout_radius" />
<attr name="layout_shadowColor" />
<attr name="layout_shadowEvaluation" />
<attr name="layout_shadowDx" />
<attr name="layout_shadowDy" />
</declare-styleable>
</resources>
--------------------- 

posted on 2019-08-01 19:15  激流勇进1  阅读(592)  评论(0编辑  收藏  举报