做Android布局是件很享受的事,这得益于他良好的xml方式。使用xml可以快速有效的为软件定义界面。可是有时候我们总感觉官方定义的一些基本组件不够用,自定义组件就不可避免了。那么如何才能做到像官方提供的那些组件一样用xml来定义他的属性呢?现在我们就来讨论一下他的用法。
  1、添加文件attrs.xml,位于res\values目录下:

<?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>

  2、创建自定义控件:

public class MyView extends View {
private Paint myPaint;
private static final String myString = "Hello CustomView!"; public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
} public MyView(Context context, AttributeSet attr) {
super(context, attr);
myPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attr, R.styleable.myView);//TypedArray是一个数组容器
float textSize = a.getDimension(R.styleable.myView_textSize, 30);//防止在XML文件里没有定义,就加上了默认值30
int textColor = a.getColor(R.styleable.myView_textColor, 0xFFFFFFFF);//同上,这里的属性是:名字_属性名
myPaint.setTextSize(textSize);
myPaint.setColor(textColor);
a.recycle();//我的理解是:返回以前取回的属性,供以后使用。以前取回的可能就是textSize和textColor初始化的那段
} @Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
myPaint.setColor(Color.RED);
myPaint.setStyle(Style.FILL);
canvas.drawRect(new Rect(10,10,100,100), myPaint);
myPaint.setColor(Color.WHITE);
canvas.drawText(myString, 10, 100, myPaint);
}
}

  3、在Activity布局文件中使用自定义控件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android">http://schemas.android.com/apk/res/android</a>"
xmlns:test="<a href="http://schemas.android.com/apk/res/com.szy.custom">http://schemas.android.com/apk/res/com.szy.custom</a>"
android:orientation="vertical"
android: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.adnroid.test.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="10px"
test:textColor="#fff"
/>
</LinearLayout>

附:Android中自定义属性的格式详解
1. reference:参考某一资源ID。
    (1)属性定义:
            <declare-styleable name = "名称">
                   <attr name = "background" format = "reference" />
            </declare-styleable>
    (2)属性使用:
             <ImageView
                     android:layout_width = "42dip"
                     android:layout_height = "42dip"
                     android:background = "@drawable/图片ID"
                     />
2. color:颜色值。
    (1)属性定义:
            <declare-styleable name = "名称">
                   <attr name = "textColor" format = "color" />
            </declare-styleable>
    (2)属性使用:
            <TextView
                     android:layout_width = "42dip"
                     android:layout_height = "42dip"
                     android:textColor = "#00FF00"
                     />
3. boolean:布尔值。
    (1)属性定义:
            <declare-styleable name = "名称">
                   <attr name = "focusable" format = "boolean" />
            </declare-styleable>
    (2)属性使用:
            <Button
                    android:layout_width = "42dip"
                    android:layout_height = "42dip"
                    android:focusable = "true"
                    />
4. dimension:尺寸值。
    (1)属性定义:
            <declare-styleable name = "名称">
                   <attr name = "layout_width" format = "dimension" />
            </declare-styleable>
    (2)属性使用:
            <Button
                    android:layout_width = "42dip"
                    android:layout_height = "42dip"
                    />
5. float:浮点值。
    (1)属性定义:
            <declare-styleable name = "AlphaAnimation">
                   <attr name = "fromAlpha" format = "float" />
                   <attr name = "toAlpha" format = "float" />
            </declare-styleable>
    (2)属性使用:
            <alpha
                   android:fromAlpha = "1.0"
                   android:toAlpha = "0.7"
                   />
6. integer:整型值。
    (1)属性定义:
            <declare-styleable name = "AnimatedRotateDrawable">
                   <attr name = "visible" />
                   <attr name = "frameDuration" format="integer" />
                   <attr name = "framesCount" format="integer" />
                   <attr name = "pivotX" />
                   <attr name = "pivotY" />
                   <attr name = "drawable" />
            </declare-styleable>
    (2)属性使用:
            <animated-rotate
                   xmlns:android = "http://schemas.android.com/apk/res/android
                   android:drawable = "@drawable/图片ID" 
                   android:pivotX = "50%" 
                   android:pivotY = "50%" 
                   android:framesCount = "12" 
                   android:frameDuration = "100"
                   />
7. string:字符串。
    (1)属性定义:
            <declare-styleable name = "MapView">
                   <attr name = "apiKey" format = "string" />
            </declare-styleable>
    (2)属性使用:
            <com.google.android.maps.MapView
                    android:layout_width = "fill_parent"
                    android:layout_height = "fill_parent"
                    android:apiKey = "0jOkQ80oD1JL9C6HAja99uGXCRiS2CGjKO_bc_g"
                    />
8. fraction:百分数。
    (1)属性定义:
            <declare-styleable name="RotateDrawable">
                   <attr name = "visible" />
                   <attr name = "fromDegrees" format = "float" />
                   <attr name = "toDegrees" format = "float" />
                   <attr name = "pivotX" format = "fraction" />
                   <attr name = "pivotY" format = "fraction" />
                   <attr name = "drawable" />
            </declare-styleable>
    (2)属性使用:
            <rotate  xmlns:android = "http://schemas.android.com/apk/res/android"
               android:interpolator = "@anim/动画ID"
                 android:fromDegrees = "0"
               android:toDegrees = "360"
                 android:pivotX = "200%"
                 android:pivotY = "300%"
               android:duration = "5000"
                 android:repeatMode = "restart"
                 android:repeatCount = "infinite"
                   />
9. enum:枚举值。
    (1)属性定义:
            <declare-styleable name="名称">
                   <attr name="orientation">
                          <enum name="horizontal" value="0" />
                          <enum name="vertical" value="1" />
                   </attr>           
            </declare-styleable>
    (2)属性使用:
            <LinearLayout
                    xmlns:android = "http://schemas.android.com/apk/res/android"
                    android:orientation = "vertical"
                    android:layout_width = "fill_parent"
                    android:layout_height = "fill_parent"
                    >
            </LinearLayout>
10. flag:位或运算。
     (1)属性定义:
             <declare-styleable name="名称">
                    <attr name="windowSoftInputMode">
                            <flag name = "stateUnspecified" value = "0" />
                            <flag name = "stateUnchanged" value = "1" />
                            <flag name = "stateHidden" value = "2" />
                            <flag name = "stateAlwaysHidden" value = "3" />
                            <flag name = "stateVisible" value = "4" />
                            <flag name = "stateAlwaysVisible" value = "5" />
                            <flag name = "adjustUnspecified" value = "0x00" />
                            <flag name = "adjustResize" value = "0x10" />
                            <flag name = "adjustPan" value = "0x20" />
                            <flag name = "adjustNothing" value = "0x30" />
                     </attr>        
             </declare-styleable>
     (2)属性使用:
            <activity
                   android:name = ".StyleAndThemeActivity"
                   android:label = "@string/app_name"
                   android:windowSoftInputMode = "stateUnspecified | stateUnchanged | stateHidden">
                   <intent-filter>
                          <action android:name = "android.intent.action.MAIN" />
                          <category android:name = "android.intent.category.LAUNCHER" />
                   </intent-filter>

</activity>
     注意:
     属性定义时可以指定多种类型值。
    (1)属性定义:
            <declare-styleable name = "名称">
                   <attr name = "background" format = "reference|color" />
            </declare-styleable>
    (2)属性使用:
             <ImageView
                     android:layout_width = "42dip"
                     android:layout_height = "42dip"
                     android:background = "@drawable/图片ID|#00FF00"
                     />

Android学习笔记_49_Android中自定义属性(attrs.xml,TypedArray的使用)的更多相关文章

  1. android开发:Android 中自定义属性(attr.xml,TypedArray)的使用

    今天我们的教程是根据前面一节扩展进行的,如果你没有看,请点击 Android高手进阶教程(三)查看第三课,这样跟容易方便你的理解! 在xml 文件里定义控件的属性,我们已经习惯了android:att ...

  2. android学习笔记----JNI中的c控制java

    面向对象的底层实现 java作为面向对象高级语言,可对现实世界进行建模.和面向过程不同的是面向对象软件的编写不是流程的堆积,而是对业务逻辑的多视角分解和分类.其过程大致为:      1).将知识分解 ...

  3. [Android学习笔记]ListView中含有Button导致无法响应onItemClick回调的解决办法

    转自:http://www.cnblogs.com/eyu8874521/archive/2012/10/17/2727882.html 问题描述: 当ListView的Item中的控件只是一些展示类 ...

  4. Android学习笔记----TimerTask中显示Toast的问题

    今天想在TimerTask的run函数中调用Toast显示一下提示信息,却总是导致程序崩溃.可是try语句块却又无法捕获到异常,代码如下: ...... Timer timer = new Timer ...

  5. Android学习笔记----Java中的字符串比较

    用习惯了C#.C++,在做字符串比较时想当然地使用如下语句: string str1 = "abcd", str2 = "abcd"; if(str1==str ...

  6. 【转】Pro Android学习笔记(十三):用户界面和控制(1):UI开发

    目录(?)[-] UI开发 方式一通过XML文件 方式二通过代码 方式三XML代码 UI开发 先理清一些UI概念: view.widget.control:这三个名词其实没有什么区别,都是一个UI元素 ...

  7. android学习笔记36——使用原始XML文件

    XML文件 android中使用XML文件,需要开发者手动创建res/xml文件夹. 实例如下: book.xml==> <?xml version="1.0" enc ...

  8. 【转】 Pro Android学习笔记(七十):HTTP服务(4):SOAP/JSON/XML、异常

    目录(?)[-] SOAP JSON和XMLPullParser Exception处理 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件,转载须注明出处:http://blog. ...

  9. 【转】 Pro Android学习笔记(三五):Menu(6):XML方式 & PopUp菜单

    目录(?)[-] 利用XML创建菜单 XML的有关属性 onClick事件 Pop-up菜单 利用XML创建菜单 在代码中对每个菜单项进行设置,繁琐且修改不灵活,不能适配多国语言的要求,可以利用资源进 ...

随机推荐

  1. STM32Cubemx出现工程突然自动退出的问题

    STM32Cubemx出现工程突然自动退出的问题 转载请注明出处,谢谢 https://www.cnblogs.com/kevin-nancy/p/10561944.html 或者 https://b ...

  2. [Activator-HelloAkka] Define our Actors

    The Actor is the unit of execution in Akka. Actors are object-oriented in the sense that they encaps ...

  3. 18 Command Line Tools to Monitor Linux Performance

    By Ravi Saive Under: Linux Commands, Monitoring Tools On: December 26, 2013 http://www.tecmint.com/c ...

  4. C# 自定义属性Attribute

    自定义属性 /// <summary> /// 脱敏属性 /// </summary> public class SensitiveAttribute:Attribute { ...

  5. MongoDB windows基础配置及集群搭建

    由于公司业务的发展MSSQL已处于瓶颈.因为没钱买牛逼服务器只能靠软件来实现最大优化了.原来的系统架构如下图:

  6. js中判断对象是否存在

    s中判断对象是否存在,写法有很多种: 第一种:if (!myObj) { var myObj = { }; }第二种:var global = this;  if (!global.myObj) {  ...

  7. C# string Stream 互转

    使用C#将字符串转化成流,将流转换成字符串,代码如下: using System.IO; using System.Text; namespace CSharpConvertString2Stream ...

  8. 02.switch的使用

    基本语法: switch-case语法: switch(表达式/变量) { case 值1: 语句块1; break; case 值2: 语句块2; break; default:语句块3; brea ...

  9. shutil模块——高级的文件、文件夹、压缩包处理模块

    将文件内容拷贝到另一个文件 shutil.copyfileobj('fsrc', 'fdst', 'length') 方法源码: def copyfileobj(fsrc, fdst, length= ...

  10. CSS中font-family:中文字体对应的英文名称

    中文字体 对应英文字体 宋体 SimSun 黑体 SimHei 微软雅黑 Microsoft YaHei 微软正黑体 Microsoft JhengHei 新宋体 NSimSun 新细明体 PMing ...