Android 自定義布局控件-圓形RelativeLayout
轉自“姜徕”,原文連結:https://blog.csdn.net/jiang001002jay/article/details/61418338
效果圖 :

建立自定義類:CircleRelativeLayout.java
package com.jzy.circularlayout;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
public class CircleRelativeLayout extends RelativeLayout {
private int color;
private int[] colors;
private int alpha;
public CircleRelativeLayout(Context context) {
super(context);
}
public CircleRelativeLayout(Context context, AttributeSet attrs) {
super(context,attrs);
init(context,attrs);
setWillNotDraw(false);
}
private void init(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs,
R.styleable.CircleRelativeLayoutLayout);
color = array.getColor(R.styleable.CircleRelativeLayoutLayout_background_color,0X0000000);
alpha = array.getInteger(R.styleable.CircleRelativeLayoutLayout_background_alpha,100);
setColors();
array.recycle();
}
@Override
protected void onDraw(Canvas canvas) { //建構圓形
int width = getMeasuredWidth();
Paint mPaint = new Paint();
mPaint.setARGB(alpha,colors[0],colors[1],colors[2]);
mPaint.setAntiAlias(true);
float cirX = width / 2;
float cirY = width / 2;
float radius = width / 2;
canvas.drawCircle(cirX, cirY, radius, mPaint);
super.onDraw(canvas);
}
public void setColor(int color) { //設定背景色
this.color = color;
setColors();
invalidate();
}
public void setAlhpa(int alhpa) { //設定透明度
this.alpha = alhpa;
invalidate();
}
public void setColors() {
int red = (color & 0xff0000) >> 16;
int green = (color & 0x00ff00) >> 8;
int blue = (color & 0x0000ff);
this.colors = new int[]{red,green,blue};
}
}
添加自定義屬性 values/attr.xml
布局檔案
擷取和設定控件 public class MainActivity extends Activity {
CircleRelativeLayout crlayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
crlayout = (CircleRelativeLayout) findViewById(R.id.crlayout);
crlayout.setColor(getResources().getColor(R.color.colorAccent));
crlayout.setAlhpa(160);
}
}