(1)给ViewGroup加一个圆角背景,同时给处于四个角的子控件加上相应的圆角。
优点:一目了然
缺点:过于麻烦。
(2)裁剪ViewGroup的范围,得到一个圆角矩形。由于本质上所谓的UI就是在一张画布上绘图,当UI有变化的时候(包括输入法光标的闪动)就重绘画布,所以限定画布的范围为一个圆角矩形就行了。优点:方便
缺点:画图麻烦,图案复杂就更麻烦了。
示例:
public class RoundLinearLayout extends LinearLayout {
private RectF rect = new RectF();
private Path path = new Path();
private Paint mPaint = new Paint();
public RoundLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
}
@Override
protected void onDraw(Canvas canvas) {
rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
mPaint.setColor(Color.BLACK);
canvas.drawRect(rect, mPaint);
path.moveTo(0, 0);
path.addRoundRect(rect, 40, 40, Direction.CW);
path.close();
canvas.clipPath(path);
mPaint.setColor(Color.WHITE);
canvas.drawRect(rect, mPaint);
super.onDraw(canvas);
}
}
显示效果:
注意事项:
ViewGroup的onDraw一般不执行,因此使用setWillNotDraw(false);可以处罚,同时给ViewGroup设置一个背景也行。