Android 自定义布局实现气泡弹窗,可控制气泡尖角方向及偏移量。
效果图
实现
首先自定义一个气泡布局。
/**
* 气泡布局
*/
public class BubbleRelativeLayout extends RelativeLayout {
/**
* 气泡尖角方向
*/
public enum BubbleLegOrientation {
TOP, LEFT, RIGHT, BOTTOM, NONE
}
public static int PADDING = 30;
public static int LEG_HALF_BASE = 30;
public static float STROKE_WIDTH = 2.0f;
public static float CORNER_RADIUS = 8.0f;
public static int SHADOW_COLOR = Color.argb(100, 0, 0, 0);
public static float MIN_LEG_DISTANCE = PADDING + LEG_HALF_BASE;
private Paint mFillPaint = null;
private final Path mPath = new Path();
private final Path mBubbleLegPrototype = new Path();
private final Paint mPaint = new Paint(Paint.DITHER_FLAG);
private float mBubbleLegOffset = 0.75f;
private BubbleLegOrientation mBubbleOrientation = BubbleLegOrientation.LEFT;
public BubbleRelativeLayout(Context context) {
this(context, null);
}
public BubbleRelativeLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BubbleRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(final Context context, final AttributeSet attrs) {
//setGravity(Gravity.CENTER);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
setLayoutParams(params);
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.bubble);
try {
PADDING = a.getDimensionPixelSize(R.styleable.bubble_padding, PADDING);
SHADOW_COLOR = a.getInt(R.styleable.bubble_shadowColor, SHADOW_COLOR);
LEG_H