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

来源:互联网 发布:淘宝注册开店要多少钱 编辑:程序博客网 时间:2024/05/22 05:28

程序员的店http://paperman.taobao.com/

插个广告,小店刚开张,欢迎各位同道中人的亲光顾,照顾生意哈,我们要做技术上滴大牛,还要穿的有范儿!酷


     一个单独继承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代码如下:

<?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 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.myViewandroid:layout_width="fill_parent" android:layout_height="fill_parent"fsms:textSize="100px" fsms:textColor="#ABCDEFEF"></com.example.android.apis.myView></LinearLayout>

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



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

//获取自定义属性          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所绘制出的图形颜色

@Overrideprotected void onDraw(Canvas canvas) {// TODO Auto-generated method stubsuper.onDraw(canvas);canvas.drawRect(new Rect(10 ,10,300,300), mPaint);}

运行结果:

源码下载链接:http://download.csdn.net/detail/bx276626237/6224049

原创粉丝点击