1. 程式人生 > >android自定義控制元件padding屬性無效的解決

android自定義控制元件padding屬性無效的解決

在自定義控制元件時,很多童鞋發現在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群英傳》一書,