Android自定义View步骤

自定义View 的步骤

  • 自定义View属性
  • 在View的构造方法中获得自定义的属性
  • 重写onMesure
  • 重写onDraw
在res/values/下建立一个attrs.xml,用来自定义View的属性
  • 定义字体的内容、颜色和大小,其中fromat的值代表了属性的值类型
  • fromat的值类型有:string、color、demension、enum、reference、float、boolean、fraction和flag
<?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的三种类型:
  • specMode = EXACTLY :设置确定的数值或者说match_parent。
  • specMode = AT_MOST :将子布局限制为一个最大值内或者说- warp_content。
  • specMode = UNSPECIFIED:表示子布局要多大就有多大,实际开发中比较少使用。
  • 重写onMesure方法主要是为了解决: 我们在使用自定义控件的时候,设置warp_content并没有按照适当缩放的效果显示出来,而是铺满显示,这个和我们预期的效果不一致。
@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);
    }
}

总结

  • 本文只是对自定义控件进行了最基础步骤的操作,需要明白最基础的View是如何自定义,为后续学习高级自定义View打下基础。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容