`

Android 中自定义控件和属性(attr.xml,declare-styleable,TypedArray)的方法和使用

 
阅读更多

今天我们的教程是根据前面一节扩展进行的,如果你没有看,请点击Android高手进阶教程(三)查看第三课,这样跟容易方便你的理解!

xml文件里定义控件的属性,我们已经习惯了android:attrs="",那么我们能不能定义自己的属性能,比如:test:attrs=""呢?答案是肯定的.

进入主题。大致以下步骤:

一、res/values文件下定义一个attrs.xml文件.代码如下:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3. <declare-styleablename="MyView">
  4. <attrname="textColor"format="color"/>
  5. <attrname="textSize"format="dimension"/>
  6. </declare-styleable>
  7. </resources>

二、我们在MyView.java代码编写如下,其中下面的构造方法是重点,我们获取定义的属性R.sytleable.MyView_textColor,获取方法中后面通常设定默认值(float textSize = a.getDimension(R.styleable.MyView_textSize,36);)防止我们在xml文件中没有定义.从而使用默认值!

MyView就是定义在<declare-styleable name="MyView"></declare-styleable>里的 名字,获取里面属性用名字_ 属性连接起来就可以.TypedArray通常最后调用.recycle()方法,为了保持以后使用该属性一致性!

  1. publicMyView(Contextcontext,AttributeSetattrs)
  2. {
  3. super(context,attrs);
  4. mPaint=newPaint();
  5. TypedArraya=context.obtainStyledAttributes(attrs,
  6. R.styleable.MyView);
  7. inttextColor=a.getColor(R.styleable.MyView_textColor,
  8. 0XFFFFFFFF);
  9. floattextSize=a.getDimension(R.styleable.MyView_textSize,36);
  10. mPaint.setTextSize(textSize);
  11. mPaint.setColor(textColor);
  12. a.recycle();
  13. }

MyView.javaMyView控件全部代码如下:

  1. packagecom.android.tutor;
  2. importandroid.content.Context;
  3. importandroid.content.res.TypedArray;
  4. importandroid.graphics.Canvas;
  5. importandroid.graphics.Color;
  6. importandroid.graphics.Paint;
  7. importandroid.graphics.Rect;
  8. importandroid.graphics.Paint.Style;
  9. importandroid.util.AttributeSet;
  10. importandroid.view.View;
  11. publicclassMyViewextendsView{
  12. privatePaintmPaint;
  13. privateContextmContext;
  14. privatestaticfinalStringmString="WelcometoMrWei'sblog";
  15. publicMyView(Contextcontext){
  16. super(context);
  17. mPaint=newPaint();
  18. }
  19. publicMyView(Contextcontext,AttributeSetattrs)
  20. {
  21. super(context,attrs);
  22. mPaint=newPaint();
  23. TypedArraya=context.obtainStyledAttributes(attrs,
  24. R.styleable.MyView);
  25. inttextColor=a.getColor(R.styleable.MyView_textColor,
  26. 0XFFFFFFFF);
  27. floattextSize=a.getDimension(R.styleable.MyView_textSize,36);
  28. mPaint.setTextSize(textSize);
  29. mPaint.setColor(textColor);
  30. a.recycle();
  31. }
  32. @Override
  33. protectedvoidonDraw(Canvascanvas){
  34. //TODOAuto-generatedmethodstub
  35. super.onDraw(canvas);
  36. //设置填充
  37. mPaint.setStyle(Style.FILL);
  38. //画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标
  39. canvas.drawRect(newRect(10,10,100,100),mPaint);
  40. mPaint.setColor(Color.BLUE);
  41. //绘制文字
  42. canvas.drawText(mString,10,110,mPaint);
  43. }
  44. }

三、将我们自定义的MyView加入布局main.xml文件中,并且使用自定义属性,自定义属性必须加上:

"xmlns:test="http://schemas.android.com/apk/res/com.android.tutor" ,test是自定义属性的前缀, com.android.tutor是我们包名.

main.xml全部代码如下:

  1. <?xml
  2. version="1.0"encoding="utf-8"?>
  3. <LinearLayout
  4. xmlns:android="http://schemas.android.com/apk/res/android"
  5. xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"
  6. android:orientation="vertical"
  7. android:layout_width="fill_parent"
  8. android:layout_height="fill_parent"
  9. >
  10. <TextView
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:text="@string/hello"
  14. />
  15. <com.android.tutor.MyView
  16. android:layout_width="fill_parent"
  17. android:layout_height="fill_parent"
  18. test:textSize="20px"
  19. test:textColor="#fff"
  20. />
  21. </LinearLayout>

四、运行之效果如下图:

参考文章二:

Android 自定义View 己经不是什么新鲜话题,Android Api提供了一大堆基础组件给我们,需要什么特定功能还需要我们继承它们然后定制更加丰富的功能。前面有篇文章也说过为自定义VIEW添加属性,但只是一笔带过,这里就拿这点来说说吧。

第一种添加属性的方法,之前我也是经常使用这种写法,代码如下:

packagecom.terry.attrs;

importandroid.content.Context;
importandroid.util.AttributeSet;
importandroid.widget.EditText;
importandroid.widget.LinearLayout;
importandroid.widget.TextView;

publicclassEditTextExt1extendsLinearLayout{

privateStringText="";

publicEditTextExt1(Contextcontext){
this(context,null);
//TODOAuto-generatedconstructorstub
}

publicEditTextExt1(Contextcontext,AttributeSetattrs){
super(context,attrs);
//TODOAuto-generatedconstructorstub
intresouceId=-1;

TextViewtv
=newTextView(context);
EditTextet
=newEditText(context);

resouceId
=attrs.getAttributeResourceValue(null,"Text",0);
if(resouceId>0){
Text
=context.getResources().getText(resouceId).toString();
}
else{
Text
="";
}
tv.setText(Text);

addView(tv);
addView(et,
newLinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
this.setGravity(LinearLayout.VERTICAL);

}

}

这种写法,简单明了,不需要额外XML的配置,就可以在我们的VIEW文件下使用。

以上代码通过构造函数中引入的AttributeSet 去查找XML布局的属性名称,然后找到它对应引用的资源ID去找值。使用也时分方便。所以一直以来我也是很喜欢这种写法。

如上,自定好VIEW文件就可以在XML布局下如此使用:

<com.terry.attrs.EditTextExt1android:id="@+id/ss3"
android:layout_width
="wrap_content"android:layout_height="wrap_content"
Text
="@string/app_name"></com.terry.attrs.EditTextExt1>

好了,这是第一种为VIEW注册属性的写法,比较简单就不多介绍。

下面是第二为VIEW注册属性的写法,这里也要重点说说第二种注册 属性的写法和使用要点,先看一下JAVA代码要如何编写:

packagecom.terry.attrs;

importandroid.content.Context;
importandroid.content.res.TypedArray;
importandroid.util.AttributeSet;
importandroid.widget.EditText;
importandroid.widget.LinearLayout;
importandroid.widget.TextView;

publicclassEditTextExtextendsLinearLayout{

publicEditTextExt(Contextcontext){
this(context,null);
//TODOAuto-generatedconstructorstub
}

publicEditTextExt(Contextcontext,AttributeSetattrs){
super(context,attrs);
//TODOAuto-generatedconstructorstub
intresouceId=-1;
TypedArraytypeArray
=context.obtainStyledAttributes(attrs,
R.styleable.EditTextExt);

TextViewtv
=newTextView(context);
EditTextet
=newEditText(context);

intN=typeArray.getIndexCount();
for(inti=0;i<N;i++){
intattr=typeArray.getIndex(i);
switch(attr){
caseR.styleable.EditTextExt_Oriental:
resouceId
=typeArray.getInt(R.styleable.EditTextExt_Oriental,
0);
this.setOrientation(resouceId==1?LinearLayout.HORIZONTAL
:LinearLayout.VERTICAL);
break;
caseR.styleable.EditTextExt_Text:
resouceId
=typeArray.getResourceId(
R.styleable.EditTextExt_Text,
0);
tv.setText(resouceId
>0?typeArray.getResources().getText(
resouceId):typeArray
.getString(R.styleable.EditTextExt_Text));
break;
}
}
addView(tv);
addView(et);
typeArray.recycle();

}

}

如上代码,跟前面代码一样。还是用的一个EDITTEXT和TEXTVIEW做基础组件。下面我们一步步分析上面的代码:

R.styleable.EditTextExt 代码的是一个attrs指向的一个declare-styleable 的标签,如下代码:

<?xmlversion="1.0"encoding="UTF-8"?>
<resources>
<declare-styleablename="EditTextExt">
<attrname="Text"format="reference|string"></attr>
<attrname="Oriental">
<enumname="Horizontal"value="1"></enum>
<enumname="Vertical"value="0"></enum>
</attr>
</declare-styleable>
</resources>

这个文件位于,values下的attrs.xml目录下面,我比较喜欢一个自定义View 对应一个declare-styleable标签。

Tip:一个自定义View 第一部分的代码,

TypedArraytypeArray=context.obtainStyledAttributes(attrs,
R.styleable.EditTextExt);

指定为一个declare-styleable,而在declare-styleable 下的attr (即各属性)Android 的ADT 将会自动生成为declare-styleable的name 名字加上“_”加上对应attr(即属性名称)的名称,如上(EditTextExt_Text)我们要得到Text 就需要R.styleable.EditTextExt_Text,这一点的话可以看看R.java生成文件:

publicstaticfinalclassstyleable{
/**AttributesthatcanbeusedwithaEditTextExt.
<p>Includesthefollowingattributes:</p>
<table>
<colgroupalign="left"/>
<colgroupalign="left"/>
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{
@link#EditTextExt_Orientalcom.terry.attrs:Oriental}</code></td><td></td></tr>
<tr><td><code>{
@link#EditTextExt_Textcom.terry.attrs:Text}</code></td><td></td></tr>
</table>
@see#EditTextExt_Oriental
@see#EditTextExt_Text
*/
publicstaticfinalint[]EditTextExt={
0x7f010000,0x7f010001
};
/**
<p>Thissymbolistheoffsetwherethe{
@linkcom.terry.attrs.R.attr#Oriental}
attribute'svaluecanbefoundinthe{
@link#EditTextExt}array.


<p>Mustbeoneofthefollowingconstantvalues.</p>
<table>
<colgroupalign="left"/>
<colgroupalign="left"/>
<colgroupalign="left"/>
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>Horizontal</code></td><td>1</td><td></td></tr>
<tr><td><code>Vertical</code></td><td>0</td><td></td></tr>
</table>
@attrnameandroid:Oriental
*/
publicstaticfinalintEditTextExt_Oriental=1;
/**
<p>Thissymbolistheoffsetwherethe{
@linkcom.terry.attrs.R.attr#Text}
attribute'svaluecanbefoundinthe{
@link#EditTextExt}array.


<p>Maybeareferencetoanotherresource,intheform"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
ortoathemeattributeintheform"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>Maybeastringvalue,using'//;'toescapecharacterssuchas'//n'or'//uxxxx'foraunicodecharacter.
@attrnameandroid:Text
*/
publicstaticfinalintEditTextExt_Text=0;
};

好了,上述的代码写完,我们要在XML布局如何使用呢?这个会跟Android 提供的基础组件的使用方法是一致的。首先,我们要为其提供一个引用包名如下:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:terry
="http://schemas.android.com/apk/res/com.terry.attrs"

上面提供的是android 基础组件的包名,和我们自己组件的包名。

写好了包名。就可以像使用andriod 基础组件一样使用了,如下全部XML布局源码:

<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:terry
="http://schemas.android.com/apk/res/com.terry.attrs"
android:orientation
="vertical"android:layout_width="fill_parent"
android:layout_height
="fill_parent">
<TextViewandroid:layout_width="fill_parent"
android:layout_height
="wrap_content"android:text="@string/hello"/>

<com.terry.attrs.EditTextExtandroid:id="@+id/ss"
android:layout_width
="fill_parent"android:layout_height="wrap_content"
terry:Text
="fdsafda"terry:Oriental="Vertical"></com.terry.attrs.EditTextExt>

<com.terry.attrs.EditTextExt1android:id="@+id/ss3"
android:layout_width
="wrap_content"android:layout_height="wrap_content"
Text
="@string/app_name"></com.terry.attrs.EditTextExt1>
</LinearLayout>


这是这两种为Android 注册 属性的使用方法,那么两者有什么区别呢?

在这里我认为起码有五点,大家可以找找看还有什么区别:

  • 第二种可以编译时报错,如果编程人员随便输入什么第一种是不会报错的,第二种可以支持代码检测功能。
  • 第二种写法,跟Android 属性标准写法是一致的,而且可以统一书法规则。
  • 第二种写法,可以支持数据格式的验证,比如我们在attrs上注明只支持integer 那么就不可以使用字符串,这是第一种达不到的。
  • 第二种写法,可以为VIEW提供选择操作,比如如上我们使用的ENUM让VIEW对应的属性支持ENUM列表,或者为其提供BOOL等只有双项选择的操作。
  • 第一种写法,所有的属性必须是引用自资源(不大确定,如果朋友有什么好的DEMO麻烦共享),第二种写法,可以即支持引用资源又可以直接输入做操作,为编程带来更多的方便性。

种种都说明,第二种写法更具规范性,功能更性,代码编写 也更优雅,但个人有个人的使用习惯,我两种都喜欢用,具体看需求吧。呵呵。。。


分享到:
评论

相关推荐

    Aj_03的Android 中自定义属性(attr.xml,TypedArray)的使用(源码)

    测试:Android 中自定义属性(attr.xml,TypedArray)的使用 注意:MyView(Context context,AttributeSet attrs)构造函数的实现, 和注意main.xml的LinearLayout 里加的声明 要了解:test:textSize="20px" test:...

    Android 中自定义属性(attr.xml,TypedArray)的使用

    NULL 博文链接:https://elingwange.iteye.com/blog/1285289

    Android中自定义控件的declare-styleable属性重用方案

    最近接触了Android自定义控件,涉及到自定义xml中得属性(attribute),其实也很简单,但是写着写着,发现代码不完美了,就是在attrs.xml这个文件中,发现属性冗余,于是就想有没有类似属性继承或者include之类的方法....

    详解Android自定义控件属性

    在Android开发中,往往要用到自定义的控件来实现我们的需求或效果。在使用自定义 控件时,难免要用到自定义属性,那怎么使用自定义属性呢? 在文件res/values/下新建attrs.xml属性文件,中定义我们所需要的属性。 ...

    Android高手进阶教程与Android基础教程

    Android高手进阶教程之----Android 中自定义属性(attr.xml,TypedArray)的使用! .doc Android高手进阶教程之----Android中万能的BaseAdapter(Spinner,ListView,GridView)的使用!.doc Android高手进阶教程之----通过...

    Android自定义Attr属性

    Android自定义Attr属性 的具体使用例子,看完之后,你就知道如何自定义控件的属性

    CircularProgress-一个模仿android L中载入视图的控件.zip

    一个模仿android L中载入视图的控件。可自定义控件的颜色、边框长度、动画时间。项目地址:https://github.com/dodocat/CircularProgress 效果图:如何使用&lt;org.quanqi.circularprogress.CircularProgressView  ...

    Android雷达图(蜘蛛网图)源码

    需要在res/values/attrs.xml中添加以下 &lt;declare-styleable name="MyNetPic"&gt; &lt;attr name="lineColor" format="color"/&gt;&lt;!-- 线的颜色 --&gt; &lt;attr name="cotentColor" format="color"/&gt;&lt;!-- 图形的颜色 --&gt; &lt;attr...

    Android自定义聊天气泡形状ImageView.rar

    Android自定义聊天气泡形状ImageView可设置箭头位置(左或右),图片圆角大小(属性在自定义attr.xml里面)

    仿qq侧滑代码

    3 在res/values/新建attr.xml,并添加如下代码 &lt;attr name="rightPadding" format="dimension"&gt;&lt;/attr&gt; &lt;declare-styleable name="MyLeftContent"&gt; &lt;attr name="rightPadding"&gt;&lt;/attr&gt; &lt;/declare-styleable&gt; ...

    GifImageView.java

    attrs.xml 属性: &lt;declare-styleable name="GifImageView"&gt; &lt;!--gif文件引用--&gt; &lt;attr name="gif_src" format="reference" /&gt; &lt;!--是否加载完自动播放--&gt; &lt;attr name="auth_play" format="boolean" /&gt; &lt;!--...

    Android自定义View中attrs.xml的实例详解

    Android自定义View中attrs.xml的实例详解 我们在自定义View的时候通常需要先完成attrs.xml文件 在values中定义一个attrs.xml 然后添加相关属性 这一篇先详细介绍一下attrs.xml的属性。 &lt;?xml version=1.0 ...

    RainyView-Android 自定义View之下雨动画 效果.zip

    画雨滴首先我们要知道一点是,所有的雨滴都是随机产生的,而产生的值,可以根据上面的自定义属性指定,也可以使用自定义的值,我们先定义一个雨滴类private class RainDrop{  float speedX; //雨滴x轴移动速度 ...

    NCURSES-Programming 文档示例程序

    |----&gt; form_win.c -- 一个简单的窗口和表单联合使用的例子 menus | |----&gt; menu_attrib.c -- 展示菜单属性的用法 |----&gt; menu_item_data.c -- 展示 item_name() 等等函数的用法 |----&gt; menu_multi_column.c...

    lottie-2.7.0.jar

    在assets文件夹下放images+json文件就可以动态生成gif的android lottie jar包,需要在自己工程里面的values/attrs.xml加上自定义属性 &lt;declare-styleable name="LottieAnimationView"&gt; &lt;attr name="lottie_fileName...

    Android代码-MultipleTheme

    真正的支持无缝换肤/夜间模式的Android框架,配合theme和换肤控件框架可以做到无缝切换换肤(无需重启应用和当前页面)。 该应用框架可以实现无缝换肤/切换夜间模式的需求,需要在换肤/切换夜间模式的界面只需要...

    linux集群基础细分视频.zip

    目录 01复习基础命令.a ...14-1attr权限 14-2根目录下每个文件的作用a 15.16sudo授权5.16.at 17-1文件系统介绍am 17-2硬链接 18查找(1) 19-1查找(2) 19-2查找(3) 20-1zip压缩 ...................

    Android-ImageView-hover:自定义 ImageView,在 ImageView 的属性中设置悬停效果

    自定义图像视图, 在 ImageView 的属性中设置悬停效果。 第 1 步:声明样式(my_styles.xml) &lt; declare xss=removed&gt; &lt; attr xss=removed xss=removed&gt; &lt; /declare-styleable &gt; 第 2 步:自定义 ImageView...

    详解Android自定义控件属性TypedArray以及attrs

    最近在研究android自定义控件属性,学到了TypedArray以及attrs。大家也可以结合《理解Android中的自定义属性》这篇文章进行学习,后续一篇还有应用。 1、attrs文件编写 &lt;?xml version=1.0 encoding=utf-8?&gt; ...

    Android自定义控件深入学习 Android生成随机验证码

    在上一篇的文章中介绍了自定义控件的属性,详情见《详解Android自定义控件属性TypedArray以及attrs》。那么在这基础上实现随机验证码生成,里面的代码是自定义控件以及涉及到自定义view绘画。 1、先看实现的效果图 ...

Global site tag (gtag.js) - Google Analytics