有时候android传统的页面布局不足以满足我们的需求,常常需要自己定义view,通常继承View,然后重写构造方法以及onDraw等函数,再具体实现自己定义的复杂view。我们知道在给控件赋属性时,通常使用的是android系统自带的属性,比如 android:layout_height="wrap_content",除此之外,我们亦可以自己定义属性,这样在使用的时候我们就可以使用形如 myapp:myTextSize="20sp"的方式了,步骤大致如下:

1、在项目文件res/value下面创建一个attr.xml文件,该文件中包含若干个attr集合,例如:

<?xml version="1.0" encoding="utf-8"?>                                      

其中resource是跟标签,可以在里面定义若干个declare-styleable。中name定义了变量的名称,下面可以再自定义多个属性,针对来说,其属性的名称为"myTextSize",format指定了该属性类型为dimension,只能表示字体的大小。

format还可以指定其他的类型比如;

reference   表示引用,参考某一资源ID

string   表示字符串

color   表示颜色值

dimension   表示尺寸值

boolean   表示布尔值

integer   表示整型值

float   表示浮点值

fraction   表示百分数

enum   表示枚举值

flag   表示位运算

 

2、在XML中的使用

<?xml version="1.0" encoding="utf-8"?>          

3、在自定义view的代码中引入自定义属性,修改构造函数

context通过调用obtainStyledAttributes方法来获取一个TypeArray,然后由该TypeArray来对属性进行设置

obtainStyledAttributes方法有三个,我们最常用的是有一个参数的obtainStyledAttributes(int[] attrs),其参数直接styleable中获得

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);

调用结束后务必调用recycle()方法,否则这次的设定会对下次的使用造成影响  

具体如下:

package com.eyu.attrtextdemo;  import android.content.Context;  import android.content.res.TypedArray;  import android.graphics.Canvas;  import android.graphics.Paint;  import android.graphics.Paint.Style;  import android.util.AttributeSet;  import android.view.View;  public class MyView extends View{      public Paint paint;      public MyView(Context context, AttributeSet attrs) {          super(context, attrs);          paint = new Paint();          TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);           int textColor = a.getColor(R.styleable.MyView_myColor, 003344);          float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);          paint.setTextSize(textSize);          paint.setColor(textColor);          a.recycle();      }      public MyView(Context context) {          super(context);          // TODO Auto-generated constructor stub      }      @Override    protected void onDraw(Canvas canvas) {          // TODO Auto-generated method stub          super.onDraw(canvas);             paint.setStyle(Style.FILL);          canvas.drawText("aaaaaaa", 10, 50, paint);      } }  

运行后:

Android 自定义属性时TypedArray的使用方法_第1张图片

-- NORMAL --

-- NORMAL --

更多相关文章

  1. Android简单自定义布局介绍
  2. Android TV 智能电视/盒子 APP 开发焦点控制 两种方法实例
  3. android v7包 正常导入使用方法
  4. Android属性动画应用超简单代码打造酷炫扇形(卫星),圆形菜单
  5. Could not find *****/adb.exe!的解决方法(android sdk太新了?**#
  6. 转帖并消化:Android中一种使用AttributeSet自定义控件的方法
  7. Android Inflate()方法用途
  8. android语音识别方法一:使用intent调用语音识别程序

随机推荐

  1. 开发者应深入学习的10个Android开源应用
  2. android 导入自己的生成的jar,老是 could
  3. Ubuntu编译Android(安卓)KitKat 4.4出现C
  4. Handler异步方式详解及其使用
  5. android开发时 使用android layout edito
  6. 转 使用HTML5开发Android本地应用(一)
  7. 基于rk3288平台android5.1系统的wifi流程
  8. [Android]使用Spring for Android改善数
  9. 安卓学习日记(一):了解安卓架构(linux内核层
  10. android 2.3 频率管理