android自定义View基础

本文详细介绍了如何在Android中自定义View,包括属性定义、构造方法实现以及事件监听的添加。通过实例展示了如何在自定义View中设置属性、重写关键方法以实现特定功能,并提供了自定义View与标准组件对比的示例。最后,通过添加点击事件实现了动态更新文本的功能,使得自定义View更加实用。同时,附录中给出了自定义属性format类型的定义及应用示例。

出处:http://blog.youkuaiyun.com/lmj623565791/article/details/24252901

很多的Android入门程序猿来说对于Android自定义View,可能都是比较恐惧的,但是这又是高手进阶的必经之路,所有准备在自定义View上面花一些功夫,多写一些文章。先总结下自定义View的步骤:

1、自定义View的属性

2、在View的构造方法中获得我们自定义的属性

[ 3、重写onMesure ]

4、重写onDraw

我把3用[]标出了,所以说3不一定是必须的,当然了大部分情况下还是需要重写的。

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

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <declare-styleable name="CustomTitleView">  
  5.         <attr name="titleText" format="string"/>  
  6.         <attr name="titleTextColor" format="color"/>  
  7.         <attr name="titleTextSize" format="dimension"/>  
  8.     </declare-styleable>  
  9.   
  10. </resources>  
我们定义了字体,字体颜色,字体大小3个属性,format是值该属性的取值类型:

一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;

关于format字段都有哪些值,在附录中我们给出其具体的定义及应用示例;

然后在布局中声明我们的自定义View

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent" >  
  6.   
  7.     <com.example.customview01.view.CustomTitleView  
  8.         android:layout_width="200dp"  
  9.         android:layout_height="100dp"  
  10.         custom:titleText="3712"  
  11.         custom:titleTextColor="#ff0000"  
  12.         custom:titleTextSize="40sp" />  
  13.   
  14. </RelativeLayout>  

一定要引入 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"我们的命名空间,后面的包路径指的是项目的package

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 文本 
  3.      */  
  4.     private String mTitleText;  
  5.     /** 
  6.      * 文本的颜色 
  7.      */  
  8.     private int mTitleTextColor;  
  9.     /** 
  10.      * 文本的大小 
  11.      */  
  12.     private int mTitleTextSize;  
  13.   
  14.     /** 
  15.      * 绘制时控制文本绘制的范围 
  16.      */  
  17.     private Rect mBound;  
  18.     private Paint mPaint;  
  19.   
  20.     public CustomTitleView(Context context, AttributeSet attrs)  
  21.     {  
  22.         this(context, attrs, 0);  
  23.     }  
  24.   
  25.     public CustomTitleView(Context context)  
  26.     {  
  27.         this(context, null);  
  28.     }  
  29.   
  30.     /** 
  31.      * 获得我自定义的样式属性 
  32.      *  
  33.      * @param context 
  34.      * @param attrs 
  35.      * @param defStyle 
  36.      */  
  37.     public CustomTitleView(Context context, AttributeSet attrs, int defStyle)  
  38.     {  
  39.         super(context, attrs, defStyle);  
  40.         /** 
  41.          * 获得我们所定义的自定义样式属性 
  42.          */  
  43.         TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);  
  44.         int n = a.getIndexCount();  
  45.         for (int i = 0; i < n; i++)  
  46.         {  
  47.             int attr = a.getIndex(i);  
  48.             switch (attr)  
  49.             {  
  50.             case R.styleable.CustomTitleView_titleText:  
  51.                 mTitleText = a.getString(attr);  
  52.                 break;  
  53.             case R.styleable.CustomTitleView_titleTextColor:  
  54.                 // 默认颜色设置为黑色  
  55.                 mTitleTextColor = a.getColor(attr, Color.BLACK);  
  56.                 break;  
  57.             case R.styleable.CustomTitleView_titleTextSize:  
  58.                 // 默认设置为16sp,TypeValue也可以把sp转化为px  
  59.                 mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(  
  60.                         TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));  
  61.                 break;  
  62.   
  63.             }  
  64.   
  65.         }  
  66.         a.recycle();  
  67.   
  68.         /** 
  69.          * 获得绘制文本的宽和高 
  70.          */  
  71.         mPaint = new Paint();  
  72.         mPaint.setTextSize(mTitleTextSize);  
  73.         // mPaint.setColor(mTitleTextColor);  
  74.         mBound = new Rect();  
  75.         mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);  
  76.   
  77.     }  

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

3、我们重写onDraw,onMesure调用系统提供的:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  3.     {  
  4.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  5.     }  
  6.   
  7.     @Override  
  8.     protected void onDraw(Canvas canvas)  
  9.     {  
  10.         mPaint.setColor(Color.YELLOW);  
  11.         canvas.drawRect(00, getMeasuredWidth(), getMeasuredHeight(), mPaint);  
  12.   
  13.         mPaint.setColor(mTitleTextColor);  
  14.         canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);  
  15.     }  
此时的效果是:

是不是觉得还不错,基本已经实现了自定义View。但是此时如果我们把布局文件的宽和高写成wrap_content,会发现效果并不是我们的预期:


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

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

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

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

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

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

下面是我们重写onMeasure代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  3. {  
  4.     int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  5.     int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
  6.     int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  7.     int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
  8.     int width;  
  9.     int height ;  
  10.     if (widthMode == MeasureSpec.EXACTLY)  
  11.     {  
  12.         width = widthSize;  
  13.     } else  
  14.     {  
  15.         mPaint.setTextSize(mTitleTextSize);  
  16.         mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);  
  17.         float textWidth = mBounds.width();  
  18.         int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());  
  19.         width = desired;  
  20.     }  
  21.   
  22.     if (heightMode == MeasureSpec.EXACTLY)  
  23.     {  
  24.         height = heightSize;  
  25.     } else  
  26.     {  
  27.         mPaint.setTextSize(mTitleTextSize);  
  28.         mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);  
  29.         float textHeight = mBounds.height();  
  30.         int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom());  
  31.         height = desired;  
  32.     }  
  33.       
  34.       
  35.   
  36.     setMeasuredDimension(width, height);  
  37. }  

现在我们修改下布局文件:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent" >  
  6.   
  7.     <com.example.customview01.view.CustomTitleView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         custom:titleText="3712"  
  11.         android:padding="10dp"  
  12.         custom:titleTextColor="#ff0000"  
  13.         android:layout_centerInParent="true"  
  14.         custom:titleTextSize="40sp" />  
  15.   
  16. </RelativeLayout>  

现在的效果是:


完全复合我们的预期,现在我们可以对高度、宽度进行随便的设置了,基本可以满足我们的需求。

当然了,这样下来我们这个自定义View与TextView相比岂不是没什么优势,所有我们觉得给自定义View添加一个事件:

在构造中添加:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. this.setOnClickListener(new OnClickListener()  
  2.         {  
  3.   
  4.             @Override  
  5.             public void onClick(View v)  
  6.             {  
  7.                 mTitleText = randomText();  
  8.                 postInvalidate();  
  9.             }  
  10.   
  11.         });  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private String randomText()  
  2.     {  
  3.         Random random = new Random();  
  4.         Set<Integer> set = new HashSet<Integer>();  
  5.         while (set.size() < 4)  
  6.         {  
  7.             int randomInt = random.nextInt(10);  
  8.             set.add(randomInt);  
  9.         }  
  10.         StringBuffer sb = new StringBuffer();  
  11.         for (Integer i : set)  
  12.         {  
  13.             sb.append("" + i);  
  14.         }  
  15.   
  16.         return sb.toString();  
  17.     }  

下面再来运行:


我们添加了一个点击事件,每次让它随机生成一个4位的随机数,有兴趣的可以在onDraw中添加一点噪点,然后改写为验证码,是不是感觉很不错。

附录:format的定义及应用示例:

1. reference:资源引用。

   属性定义:

<attr name = "background" format = "reference" />

  属性使用:  

<com.lin.gw.CustomView
   android:layout_width = "42dip"
   android:layout_height = "42dip"
   app:background = "@drawable/图片ID"
/>

2. color:颜色值。

    属性定义:       

<attr name = "textColor" format = "color" />

    属性使用:

<com.lin.gw.CustomView
   android:layout_width = "42dip"
   android:layout_height = "42dip"
   app:textColor = "#fff000"
/>

3. boolean:布尔值。

    属性定义:

<attr name = "focusable" format = "boolean" />

    属性使用:

<com.lin.gw.CustomView
   android:layout_width = "42dip"
   android:layout_height = "42dip"
   app:focusable = "true"
/>

4. dimension:尺寸值。

    属性定义:

<attr name = "customWidth" format = "dimension" />

    属性使用:

<com.lin.gw.CustomView
   app:customWidth = "42dip"
   android:layout_height = "wrap_content"
/>

5. float:浮点值。

    属性定义:

<attr name = "fromAlpha" format = "float" />

    属性使用:

<com.lin.gw.CustomView
   app:fromAlpha = "2.0"
/>

 

6. integer:整型值。

    属性定义:                  

<attr name = "frameDuration" format="integer" />        

    属性使用:

<com.lin.gw.CustomView
   app:frameDuration = "20"
/>

7. string:字符串。

  属性定义:

<attr name="textString"  format="string"></attr>

    属性使用:

<com.lin.gw.CustomView
   app:textString = "hello lingling!"
/>

8. fraction:百分数。

    属性定义:          

<attr name = "pivotX" format = "fraction" />

  属性使用:

<com.lin.gw.CustomView
   app:pivotX = "30%"
/>

9. enum:枚举值。

    属性定义:

<attr name="orientation">
   <enum name="horizontal" value="0" />
   <enum name="vertical" value="1" />
 </attr>      

    属性使用:

<com.lin.gw.CustomView
   app:orientation = "vertical"
/>

10. flag:位或运算。

     属性定义:          

复制代码
<declare-styleable name="CustomView">
     <attr name="windowSoftInputMode">
           <flag name = "stateUnspecified" value = "0" />
           <flag name = "stateUnchanged" value = "1" />
           <flag name = "stateHidden" value = "2" />
           <flag name = "stateAlwaysHidden" value = "3" />
           <flag name = "stateVisible" value = "4" />
           <flag name = "stateAlwaysVisible" value = "5" />
           <flag name = "adjustUnspecified" value = "0x00" />
           <flag name = "adjustResize" value = "0x10" />
           <flag name = "adjustPan" value = "0x20" />
           <flag name = "adjustNothing" value = "0x30" />
     </attr>         
</declare-styleable>
复制代码

     属性使用:

app:windowSoftInputMode = "stateUnspecified | stateUnchanged | stateHidden">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值