自定义控件1--自定义属性


自定义控件是进阶的必经之路,整理一下自定义控件的知识.分享给大家.


1.自定义view属性

在values下建立一个xml文件,最好以attrs什么的开头,好区分,我这里建立了一个attrs_myview.xml的文件.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="radios" format="integer"/>
        <attr name="mycolor" format="color"/>
    </declare-styleable>
</resources>


2,声明

a,通用方式:xmlns:app="http://schemas.android.com/apk/res-auto"

b,一般方式xmlns:custom="http://schemas.android.com/apk/res/我的包名" 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.king.myapplication.MainActivity">


    <com.example.king.myapplication.MyView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff0000"
        android:padding="20dp"
        app:radios="200"
        app:mycolor="#00aaff"
        />

</RelativeLayout>

3,使用

得到方式也有两种,不过基本上也是一个意思的.

方式一

        TypedArray arry = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        radius = (int)arry.getInteger(R.styleable.MyView_radios, 0);
        mColor = arry.getColor(R.styleable.MyView_mycolor, Color.GREEN);
        arry.recycle();

方式二

        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyleAttr, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++)
        {
            int attr = a.getIndex(i);
            switch (attr)
            {
                case R.styleable.MyView_radios:
                    radius = a.getInteger(attr,0);
                    break;
                case R.styleable.MyView_mycolor:
                    // 默认颜色设置为黑色
                    mColor = a.getColor(attr, Color.BLACK);
                    break;

            }

        }
        a.recycle();


3.重写onMeasure();

setMeasuredDimension方法设置当前view的宽高,

这里要注意的一点事但我们设置为wrapContext其实是不起作用的,需要自己来配置.我简单些一下来看看

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(radius * 2 + paddingLeft + paddingRight, radius * 2 + paddingtop + paddingBottom);
    }


4.重写onDraw();

在onDraw方法中我们可以图形和文字.

这里值得注意的是我们需要先初始化一个画笔,画笔会初始化一些绘图的属性,比如颜色,字体大小等等

但是绘图方法要在canvas(画布)中来做


        mpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mpaint.setColor(mColor);
        mTextpaint.setColor(Color.BLACK);
        mTextpaint.setTextSize(50);

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        canvas.drawCircle(radius + paddingLeft, radius + paddingtop, radius, mpaint);
        canvas.drawText(mText, width / 2 - paddingLeft, height / 2 - paddingtop, mTextpaint);
    }


5.看个整体demo代码


package com.example.king.myapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * Created by king on 2016/3/21.
 */
public class MyView extends View{
    private int radius = 300;
    private Paint mpaint;
    private int paddingLeft;
    private int paddingtop;
    private int paddingRight;
    private int paddingBottom;
    private Paint mTextpaint;
    private int mColor;
    private String mText="hehe";

    public MyView(Context context) {
        super(context);
        init();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray arry = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        radius = (int)arry.getInteger(R.styleable.MyView_radios, 0);
        mColor = arry.getColor(R.styleable.MyView_mycolor, Color.GREEN);
        arry.recycle();
        init();
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        /**
         * 获得我们所定义的自定义样式属性
         */
        //方式一
        TypedArray arry = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        radius = (int)arry.getInteger(R.styleable.MyView_radios, 0);
        mColor = arry.getColor(R.styleable.MyView_mycolor, Color.GREEN);
        arry.recycle();

        //方式二
//        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyleAttr, 0);
//        int n = a.getIndexCount();
//        for (int i = 0; i < n; i++)
//        {
//            int attr = a.getIndex(i);
//            switch (attr)
//            {
//                case R.styleable.MyView_radios:
//                    radius = a.getInteger(attr,0);
//                    break;
//                case R.styleable.MyView_mycolor:
//                    // 默认颜色设置为黑色
//                    mColor = a.getColor(attr, Color.BLACK);
//                    break;
//
//            }
//
//        }
//        a.recycle();

        init();




    }

    private void init() {
        mpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mpaint.setColor(mColor);
        mTextpaint.setColor(Color.BLACK);
        mTextpaint.setTextSize(50);
        paddingLeft = getPaddingLeft();
        paddingtop = getPaddingTop();
        paddingRight = getPaddingRight();
        paddingBottom = getPaddingBottom();
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mText = randomText();
                postInvalidate();
            }
        });
    }
    private String randomText()
    {
        Random random = new Random();
        Set<Integer> set = new HashSet<Integer>();
        while (set.size() < 4)
        {
            int randomInt = random.nextInt(10);
            set.add(randomInt);
        }
        StringBuffer sb = new StringBuffer();
        for (Integer i : set)
        {
            sb.append("" + i);
        }

        return sb.toString();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(radius * 2 + paddingLeft + paddingRight, radius * 2 + paddingtop + paddingBottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        canvas.drawCircle(radius + paddingLeft, radius + paddingtop, radius, mpaint);
        canvas.drawText(mText, width / 2 - paddingLeft, height / 2 - paddingtop, mTextpaint);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);


    }
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值