自定义view

Android自定义View步骤

2017-09-03  本文已影响15人  奕晴天

自定义View 的步骤

在res/values/下建立一个attrs.xml,用来自定义View的属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--字体-->
    <attr name="titleContent" format="string"/>
    <!--字体颜色-->
    <attr name="customTextColor" format="color"/>
    <!--字体大小-->
    <attr name="customTitleTextSize" format="dimension"/>

    <declare-styleable name="CustomTitleView">
        <attr name="titleContent"/>
        <attr name="customTextColor"/>
        <attr name="customTitleTextSize"/>
    </declare-styleable>
</resources>
CustomTitleView.java
重写CustomTitleView的构造函数,来获取自定义的属性
public class CustomTitleView extends View {

    String mTitleText;
    int mTitleTextColor;
    int mTitleTextSize;
    Rect mBound;
    Paint mPaint;

    public CustomTitleView(Context context) {
        this(context,null);
    }

    public CustomTitleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CustomTitleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView,defStyleAttr,0);
        int n = typedArray.getIndexCount();
        for (int i=0;i<n;i++){
            int attr = typedArray.getIndex(i);
            switch (attr){
                case R.styleable.CustomTitleView_titleContent:
                    mTitleText = typedArray.getString(attr);
                    break;
                case R.styleable.CustomTitleView_customTextColor:
                    mTitleTextColor = typedArray.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.CustomTitleView_customTitleTextSize:
                    mTitleTextSize = typedArray.getDimensionPixelSize(attr,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics()));
                    break;
            }
        }
        typedArray.recycle();

        mPaint = new Paint();
        mPaint.setTextSize(mTitleTextSize);
        mBound = new Rect();
        mPaint.getTextBounds(mTitleText,0,mTitleText.length(),mBound);

    }
}
重写onMesure时,需要知道MeasureSpec的三种类型:
@Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       int widthMode = MeasureSpec.getMode(widthMeasureSpec);
       int widthSize = MeasureSpec.getSize(widthMeasureSpec);
       int heightMode = MeasureSpec.getMode(heightMeasureSpec);
       int heightSize = MeasureSpec.getSize(heightMeasureSpec);
       int width;
       int height;
       if (widthMode == MeasureSpec.EXACTLY){
           width = widthSize;
       }else {
           mPaint.setTextSize(mTitleTextSize);
           mPaint.getTextBounds(mTitleText,0,mTitleText.length(),mBound);
           float textWidth = mBound.width();
           int desired = (int)(getPaddingLeft()+textWidth+getPaddingRight());
           width = desired;
       }

       if (heightMode == MeasureSpec.EXACTLY){
           height = heightSize;
       }else {
           mPaint.setTextSize(mTitleTextSize);
           mPaint.getTextBounds(mTitleText,0,mTitleText.length(),mBound);
           float textHeight = mBound.height();
           int desired = (int)(getPaddingTop()+textHeight+getPaddingBottom());
           height = desired;
       }
       setMeasuredDimension(width,height);
   }

重写onDraw函数,根据读取到的自定义属性,绘制出相应的控件
@Override
    protected void onDraw(Canvas canvas) {
        mPaint.setColor(Color.YELLOW);
        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),mPaint);
        mPaint.setColor(mTitleTextColor);
        canvas.drawText(mTitleText,getWidth()/2-mBound.width()/2,getHeight()/2+mBound.height()/2,mPaint);
    }
activity_cutsom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto/"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.liuyican.interview.customview.CustomTitleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:padding="10dp"
        custom:titleContent="HelloWorld"
        custom:customTextColor="#ff0000"
        custom:customTitleTextSize="40sp"
        />

</LinearLayout>
CustomActivity.java
package com.example.liuyican.interview.customview;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.example.liuyican.interview.R;
import com.example.liuyican.interview.overalldialog.BaseActivity;

/**
 * Created by liuyican on 2017/9/2.
 */

public class CustomActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cutsom);
    }
}

总结

上一篇下一篇

猜你喜欢

热点阅读