安卓自定义控件

安卓自定义控件

## 安卓自定义控件
自定义步骤
view工作原理
自定义View的属性
重写构造方法

自定义步骤

    了解View的工作原理
编写继承自View的子类
为自定义View类增加属性
绘制控件
响应用户消息
自定义回调函数

view工作原理

Android系统的视图结构的设计也采用了组合模式,即View作为所有图形的基类,Viewgroup对View继承扩展为视图容器类。

View定义了绘图的基本操作
基本操作由三个函数完成:measure()、layout()、draw(),其内部又分别包含了onMeasure()、onLayout()、onDraw()三个子方法。

具体操作如下:

1. measure操作

measure操作主要用于计算视图的大小,即视图的宽度和长度。在view中定义为final类型,要求子类不能修改。measure()函数中又会调用下面的函数:

(1)onMeasure(),视图大小的将在这里最终确定,也就是说measure只是对onMeasure的一个包装,子类可以覆写onMeasure()方法实现自己的计算视图大小的方式,并通过setMeasuredDimension(width, height)保存计算结果。

2. layout操作

layout操作用于设置视图在屏幕中显示的位置。在view中定义为final类型,要求子类不能修改。layout()函数中有两个基本操作:

(1)setFrame(l,t,r,b),l,t,r,b即子视图在父视图中的具体位置,该函数用于将这些参数保存起来;

(2)onLayout(),在View中这个函数什么都不会做,提供该函数主要是为viewGroup类型布局子视图用的;

3. draw操作

draw操作利用前两部得到的参数,将视图显示在屏幕上,到这里也就完成了整个的视图绘制工作。子类也不应该修改该方法,因为其内部定义了绘图的基本操作:

(1)绘制背景;

(2)如果要视图显示渐变框,这里会做一些准备工作;

(3)绘制视图本身,即调用onDraw()函数。在view中onDraw()是个空函数,也就是说具体的视图都要覆写该函数来实现自己的显示(比如TextView在这里实现了绘制文字的过程)。而对于ViewGroup则不需要实现该函数,因为作为容器是“没有内容“的,其包含了多个子view,而子View已经实现了自己的绘制方法,因此只需要告诉子view绘制自己就可以了,也就是下面的dispatchDraw()方法;

(4)绘制子视图,即dispatchDraw()函数。在view中这是个空函数,具体的视图不需要实现该方法,它是专门为容器类准备的,也就是容器类必须实现该方法;

(5)如果需要(应用程序调用了setVerticalFadingEdge或者setHorizontalFadingEdge),开始绘制渐变框;

(6)绘制滚动条;
从上面可以看出自定义View需要最少覆写onMeasure()和onDraw()两个方法。
自定义View的属性.

首先在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式

    <?xml version="1.0" encoding="utf-8"?>  
    <resources>  

<attr name="titleText" format="string" />  
<attr name="titleTextColor" format="color" />  
<attr name="titleTextSize" format="dimension" />  

<declare-styleable name="CustomTitleView">  
    <attr name="titleText" />  
    <attr name="titleTextColor" />  
    <attr name="titleTextSize" />  
</declare-styleable>  

    </resources>  

我们定义了字体,字体颜色,字体大小3个属性,format是值该属性的取值类型,然后在布局中声明我们的自定义View

xmlns:tools="http://schemas.android.com/tools"  
xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"  
android:layout_width="match_parent"  
android:layout_height="match_parent" >  

<com.example.customview.view.CustomTitleView  
    android:layout_width="200dp"  
    android:layout_height="100dp"  
    custom:titleText="3712"  
    custom:titleTextColor="#ff0000"  
    custom:titleTextSize="40sp" />  

    </RelativeLayout>  

在View的构造方法中,获得我们的自定义的样式

private int mTitleTextColor;  
private int mTitleTextSize;  
private Rect mBound;  
private Paint mPaint;  

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

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

/** 
 * 获得我自定义的样式属性 
 *  
 * @param context 
 * @param attrs 
 * @param defStyle 
 */  
public CustomTitleView(Context context, AttributeSet attrs, int defStyle)  
{  
    super(context, attrs, defStyle);  
    /** 
     * 获得我们所定义的自定义样式属性 
     */  
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);  
    int n = a.getIndexCount();  
    for (int i = 0; i < n; i++)  
    {  
        int attr = a.getIndex(i);  
        switch (attr)  
        {  
        case R.styleable.CustomTitleView_titleText:  
            mTitleText = a.getString(attr);  
            break;  
        case R.styleable.CustomTitleView_titleTextColor:  
            // 默认颜色设置为黑色  
            mTitleTextColor = a.getColor(attr, Color.BLACK);  
            break;  
        case R.styleable.CustomTitleView_titleTextSize:  
            // 默认设置为16sp,TypeValue也可以把sp转化为px  
            mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(  
                    TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));  
            break;  
        }  
    }  
    a.recycle();  
    /** 
     * 获得绘制文本的宽和高 
     */  
    mPaint = new Paint();  
    mPaint.setTextSize(mTitleTextSize);  
    // mPaint.setColor(mTitleTextColor);  
    mBound = new Rect();  
    mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);  
}

重写构造方法

默认的布局文件调用的是两个参数的构造方法,所以记得让所有的构造调用我们的三个参数的构造,我们在三个参数的构造中获得自定义属性。

重写onDraw,onMesure调用系统提供的:

    @Override  
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
{  
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
}  

@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);  
} 

系统帮我们测量的高度和宽度都是MATCH_PARNET,当我们设置明确的宽度和高度时,系统帮我们测量的结果就是我们设置的结果,当我们设置为WRAP_CONTENT,或者MATCH_PARENT系统帮我们测量的结果就是MATCH_PARENT的长度。

所以,当设置了WRAP_CONTENT时,我们需要自己进行测量,即重写onMesure方法”:

重写之前先了解MeasureSpec的specMode,一共三种类型:

EXACTLY:一般是设置了明确的值或者是MATCH_PARENT

AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT

UNSPECIFIED:表示子布局想要多大就多大,很少使用

下面是我们
重写onMeasure代码:

    @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(mTitle, 0, mTitle.length(), mBounds);  
    float textWidth = mBounds.width();  
    int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());  
    width = desired;  
}  

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



setMeasuredDimension(width, height);  

重写onDraw()

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);  
}  

作者:施彬彬:原文地址

你可能感兴趣的:(android)