在自定义控件时,很多童鞋发现在XML布局中写上padding属性却不起作用,而且wrap_content和march_parent显示效果一样,这就需要我们在代码中对自定义View宽高做相应的改动,以自定义一个简单的圆示例,如下图(加了padding属性):
代码如下:
public class CircleView extends View {
private Paint mPaint;
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public CircleView(Context context) {
super(context);
initView();
}
private void initView() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(8);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//对宽高的测量
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode==MeasureSpec.AT_MOST&&heightMode==MeasureSpec.AT_MOST) {
setMeasuredDimension(300, 100);
}else if (widthMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(300, heightSize);
}else if (heightMode ==MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSize, 100);
}
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
int paddingBottom = getPaddingBottom();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
//主要是考虑到VIEW周围的空白
int width = getWidth()-paddingLeft-paddingRight;
int height = getHeight()-paddingTop-paddingBottom;
int radius = Math.min(width, height)/2;
canvas.drawCircle(paddingLeft+width/2, paddingTop+height/2, radius, mPaint);
}
}
circle.xml布局代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<com.example.customview.CircleView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_margin="20dp"
android:background="#000000"
android:padding="20dp" />
</LinearLayout>
关于自定义view,可以参考《android开发艺术探索》《android群英传》一书,