Android单独继承View类来实现自定义控件

一个单独继承view类来实现自定义控件,在该方法中,需要重写ondraw方法来绘制自己所需要的控件,下面也以一个简单的例子来说明如何实现自定义控件。该方法可以实现所需要的所有的自定义控件。

属性文件中format可选项 

    自定义控件就需要首先自定义该控件的属性。在开始前,我们需要检查在values目录下是否有attrs.xml,如果没有则创建。下面我们先来了解一下format属性类型都有哪些。

 

format可选项

l"reference" //引用
l"color" //颜色
l "boolean" //布尔值
l "dimension" //尺寸值
l "float" //浮点值
l "integer" //整型值
l "string" //字符串
l "fraction" //百分数 比如200%

 

attrs.xml代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3. <declare-styleable name="myView">  
  4. <attr name="textColor" format="color" />  
  5. <attr name="textSize" format="dimension" />  
  6. </declare-styleable>  
  7. </resources>  

在Layout文件夹中,修改main.xml,在其中引用MyView

 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:fsms="http://schemas.android.com/apk/res/com.example.android.apis"  
  4.     android:orientation="vertical"   
  5.     andrid:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent">  
  7.     <TextView   
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"   
  10.         android:text="@string/hello" />  
  11.     <com.example.android.apis.myView  
  12.         android:layout_width="fill_parent"   
  13.         android:layout_height="fill_parent"  
  14.         fsms:textSize="100px"   
  15.         fsms:textColor="#ABCDEFEF">  
  16.         </com.example.android.apis.myView>  
  17. </LinearLayout>  

 

添加了MyView ,并设置textSizetextColor,需注意此行:xmlns:fsms="http://schemas.android.com/apk/res/com.example.android.apis"

 

 

 

主程序中获取控件属性,并设置默认值。

 

  1. //获取自定义属性    
  2.         TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myView);    
  3.         //获取尺寸属性值,默认大小为:30    
  4.         float textSize = a.getDimension(R.styleable.myView_textSize, 30);    
  5.         //获取颜色属性值,默认颜色为:0x990000FF    
  6.         int textColor = a.getColor(R.styleable.myView_txtColor, 0x990000FF);    
  7.         //设置画笔的尺寸和颜色    

 

最后,我们需要注意的是覆写的onDraw()方法,此方法中构造了一个矩形,而这个矩形的构造则用到了我们之前设置的文本线条宽度及Paint所绘制出的图形颜色

 

  1. @Override  
  2. protected void onDraw(Canvas canvas) {  
  3. // TODO Auto-generated method stub  
  4. super.onDraw(canvas);  
  5. canvas.drawRect(new Rect(10 ,10,300,300), mPaint);  
  6. }  
运行结果:
posted @ 2013-09-25 09:56  Pepper.B  阅读(362)  评论(0编辑  收藏  举报