志在指尖
用双手敲打未来

Android 自定义 View 以及以及 layout 属性全攻略

关于Android系统的自定义View可能大家都熟习了,关于自定义View的属性添加,以及Android的Layout的命名空
间问题,很多网友还不是很分明,今天Android123一同再带大家复习一下
CwjViewmyView=newCwjView(context);
假如用于游戏或整个窗体的界面,
我们可能直接在onCreate中setContentView(myView);当然假如是控件,我们可能会需求从Layout的xml中声明,比

<cn.com.android123.CwjView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
/>
当然,我们也能够直接从父类声明比方
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
/>
上面我们仅用了父类View的两个属性,均来自android命名空间,而称号为layout_width或layout_height,我们自
定义的控件可能有更多的功用,比方
<cn.com.android123.CwjView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
cwj:age=”22″
cwj:university=”sjtu”
cwj:city=”shanghai”
/>
我们能够看到上面的三个属性,是我们自定义的。Android
作为规范xml标准,可能还包含了相似
xmlns:android=”http://schemas.android.com/apk/res/android”这样的语句,关于定义完好的View,我们的命名空
间为cwj,
这里能够写为
xmlns:cwj=http://schemas.android.com/apk/res/cn.com.android123.cwjView或
xmlns:cwj=http://schemas.android.com/apk/res/android都能够。
关于定义的cwj命名空间和age、university以及city的三个属性我们如何定义呢?在工程的res/values目录中我们
新建一个cwj_attr.xml文件,编码方式为utf-8是一个好习气,内容如下
<?xmlversion=”1.0″encoding=”utf-8″?>
<declare-styleablename=”CwjView”>
这里我们可能对format不是很熟习,目前Android系统内置的格式类型有integer比方ProgressBar的进度值,float
比方RatingBar的值可能是3.5颗星,boolean比方ToggleButton的能否勾选,string比方TextView的text属性,
当然除了我们常见的根底类型外,Android的属性还有特殊的比方color是用于颜色属性的,能够辨认为#FF0000等类
型,当然还有dimension的尺寸类型,比方23dip,15px,18sp的长度单位,还有一种特殊的为reference,普通用于
援用@+id/cwj@drawable/xxx这样的类型。当然什么时分用reference呢?我们就以定义一个颜色为例子,<attr
name=”red”format=”color|reference”/>这里我们用了逻辑或的运算符,定义的红色是颜色类型的,同时能够被引
用当然,关于我们自定义的类中,我们需求运用一个名为obtainStyledAttributes的办法来获取我们的定义。在我
们自定义View的结构办法(Contextcontext,AttributeSetattrs)的重载类型中能够用
publicCwjView(Contextcontext,AttributeSetattrs){
super(context,attrs);
TypedArraya=context.obtainStyledAttributes(attrs,R.styleable.cwj_attr);
mAge=a.getInteger(R.styleable.CwjView_age,22);
mCity=a.getString(R.styleable.CwjView_city,”shanghai”);
mUniversity=a.getString(R.styleable.CwjView_university,”sjtu”);
a.recycle();//Android123提示大家不要忘了回收资源
}
这样类的全局成员变量mAge、mCity就获取了我们需求的内容,当然依据layout中的数值我们自定义的CwjView需求
动态的处置一些数据的状况,能够运用AttributeSet类的getAttributeResourceValue办法获取。
publicCwjView(Contextcontext,AttributeSetattrs)
{
super(context,attrs);
resId=attrs.getAttributeResourceValue(“cn.com.android123.CwjView”,”age”,100);
resId=attrs.getAttributeResourceValue(“cn.com.android123.CwjView”,”city”,”shanghai”);
//resID就能够恣意运用了
}
以上两种办法中,参数的最后一个数值为默许的,假如您有不明白的中央能够来函到android123@163.com我们会在第
一时间回复。

未经允许不得转载:IT技术网站 » Android 自定义 View 以及以及 layout 属性全攻略
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载