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 ,并设置textSize和textColor,需注意此行: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
- Android单独继承View类来实现自定义控件
- 【代码】Android 单独继承View类来实现自定义控件
- android继承View实现复杂的自定义控件(1)
- Android自定义控件10----继承View实现水波纹效果
- android自定义控件(二) 入门,继承View
- android自定义控件(二) 入门,继承View
- Android-自定义控件之继承View
- android自定义控件(二) 入门,继承View
- android自定义控件(二) 入门,继承View
- Android 如何自定义控件(继承View)
- Android 自定义控件之继承view
- 继承View自定义控件
- 自定义控件-继承View
- android自定义View之重写View来实现全新的控件
- Android自定义控件View(二)继承控件
- Android自定义控件-完全自定义(继承View ,ViewGroup)
- android自定义View-继承
- 自定义控件之 继承 View
- 判断二进制数中1的个数
- 二、使用OCUnit
- Win32 Series - Becoming a Clipboard Viewer
- Javascript中的replaceAll
- 师傅经验教导
- Android单独继承View类来实现自定义控件
- eclipse 设置。调优。使用
- Unix/Linux上进程标识赋值方法
- jQuery 自学笔记—10 常见特效 (终章)
- js封装的MAP
- 嗯,让我们彻底搞懂C/C++函数指针吧
- ffmpeg分析系列之三(输入输出格式)
- 一个简单的网页抓取例子
- 简单使用游标插入数据