【代码】Android 单独继承View类来实现自定义控件

一个单独继承view类来实现自定义控件,在该方法中,需要重写ondraw方法来绘制自己所需要的控件,下面也以一个简单的例子来说明如何实现自定义控件。该方法可以实现所需要的所有的自定义控件。
 (PS:^_^不错的 Android学习交流群278744577,验证: csl,有兴趣的话可以加入进来一起讨论)
属性文件中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代码如下:
Xml代码  
<?xml version="1.0" encoding="utf-8"?>    
<resources>    
<declare-styleable name="myView">    
<attr name="textColor" format="color" />    
<attr name="textSize" format="dimension" />    
</declare-styleable>    
</resources>   

在Layout文件夹中,修改main.xml,在其中引用MyView
Xml代码  
<?xml version="1.0" encoding="utf-8"?>    
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    xmlns:fsms="http://schemas.android.com/apk/res/com.example.android.apis"    
    android:orientation="vertical"     
    andrid:layout_width="fill_parent"    
    android:layout_height="fill_parent">    
    <TextView     
        android:layout_width="fill_parent"    
        android:layout_height="wrap_content"     
        android:text="@string/hello" />    
    <com.example.android.apis.myView    
        android:layout_width="fill_parent"     
        android:layout_height="fill_parent"    
        fsms:textSize="100px"     
        fsms:textColor="#ABCDEFEF">    
        </com.example.android.apis.myView>    
</LinearLayout>  

  
添加了MyView ,并设置textSize和textColor,需注意此行:xmlns:fsms=http://schemas.android.com/apk/res/com.example.android.apis
 
 
主程序中获取控件属性,并设置默认值
Java代码  
 //获取自定义属性      
 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myView);      
 //获取尺寸属性值,默认大小为:30      
 float textSize = a.getDimension(R.styleable.myView_textSize, 30);      
 //获取颜色属性值,默认颜色为:0x990000FF      
 int textColor = a.getColor(R.styleable.myView_txtColor, 0x990000FF);      
 //设置画笔的尺寸和颜色   

   
最后,我们需要注意的是覆写的onDraw()方法,此方法中构造了一个矩形,而这个矩形的构造则用到了我们之前设置的文本线条宽度及Paint所绘制出的图形颜色
Java代码  
@Override    
protected void onDraw(Canvas canvas) {    
// TODO Auto-generated method stub    
super.onDraw(canvas);    
canvas.drawRect(new Rect(10 ,10,300,300), mPaint);    
}    
 

运行结果:

https://i-blog.csdnimg.cn/blog_migrate/5d9f8cc17256014e1583f8d127c1b413.png

 
源码下载链接:http://download.csdn.net/detail/bx276626237/6224049
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值