什么是自定义控件?
首先你要知道什么是控件:如TextView、WebView等,他们是View的子类,他们存在于androidSDK中platforms文件夹下android.jar中依赖于你的项目。
在你的xml布局文件中你需要在你的根Layout标签下声明XML Namespaces (XML的命名空间)
xmlns:android="http://schemas.android.com/apk/res/android" 这样XML就能找到android.jar中的控件了。
同样要调用自定义控件需要xmlns:aaaa="http://schemas.android.com/apk/res/bbbb" aaaa为命名空间标记,让系统记录在案,你在要以此名称引用你的自定义属性。
bbbb是你项目的包名。
如此引用
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.customview01.view.CustomTitleView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:id="@+id/q1" custom:CTextColor="#ff0000"
custom:Cext="3712" custom:CTextSize="40sp" />
属性设置与属性获取
一个控件如何从你的脑海便成现实呢,你要描述它,设置他的属性,如下设置:
在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式,android中
我们的自定义控件类从XML资源获取到这些属性
如此
<?xml version="1.0" encoding="utf-8"?><resources> <attr name="CText" format="string" /> <attr name="CTextColor" format="color" /> <attr name="CTextSize" format="dimension" /> <declare-styleable name="CustomTextView"> <attr name="CText" /> <attr name="CTextColor" /> <attr name="CTextSize" /> </declare-styleable></resources>
换一个顺序叙述,我们先创建自定义控件类,起一个名字比如CustomTextView,让他继承View
最终效果用户会设置这个控件的各个属性,而我们这个类要做的就是处理用户设置的各个属性,使他们完成使命。
大概通过构造()及重写View的onMeasure()onDraw()方法完成绘制
这样就可以写出各种各样的控件了,具体写法与API不在此文范畴。 可参考

新闻热点
疑难解答