博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android -- TypedArray
阅读量:7260 次
发布时间:2019-06-29

本文共 2033 字,大约阅读时间需要 6 分钟。

当我们自定义View的时候,在给View赋值一些长度宽度的时候,一般都是在layout布局文件中进行的。,比如android:layout_height="wrap_content",除此之外,我们也可以自己定义属性,这样在使用的时候我们就可以使用形如 myapp:myTextSize="20sp"的方式了。

values/attrs.xml

首先要创建变量,创建了个values/attrs.xml文件,或文件名任意,但是要在values目录下:

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

  • format还可以指定其他的类型比如:
  • reference   表示引用,参考某一资源ID
  • string   表示字符串
  • color   表示颜色值
  • dimension   表示尺寸值
  • boolean   表示布尔值
  • integer   表示整型值
  • float   表示浮点值
  • fraction   表示百分数
  • enum   表示枚举值
  • flag   表示位运算

layout

可以看到多了xmlns:myapp="http://schemas.android.com/apk/res/com.eyu.attrtextdemo" ,以及在自定义View中 myapp:textSize="20sp" ,myapp:myColor="#324243" 

obtainStyledAttributes

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

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

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

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

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);      }            @Override     protected void onDraw(Canvas canvas) {          super.onDraw(canvas);             paint.setStyle(Style.FILL);          canvas.drawText("aaaaaaa", 10, 50, paint);      }        }

我是天王盖地虎的分割线

本文转自我爱物联网博客园博客,原文链接:http://www.cnblogs.com/yydcdut/p/4251572.html,如需转载请自行联系原作者

你可能感兴趣的文章
【转】tcp链接的状态
查看>>
Android Studio检测内存泄露和性能
查看>>
Ubuntu安装JDK配置环境变量
查看>>
YUV格式详细解释
查看>>
Python 基础 函数
查看>>
VMware虚拟机出现Reason: Failed to lock the file
查看>>
《BOOST程序库完全开发指南》 第11章 函数与回调
查看>>
lettuce webdriver 自动化测试---玩转BDD
查看>>
python基础补充内容
查看>>
Python之路【第一篇】:Python基础(2)
查看>>
728. Self Dividing Numbers
查看>>
gravity
查看>>
LeetCode 657. Robot Return to Origin
查看>>
小试Express
查看>>
Windows Live Writer 工具插件
查看>>
PHP上传图片到数据库和存储到本地文件夹的方法
查看>>
php动物书总结01-06
查看>>
计算当前日期是一年中的第几周
查看>>
fzu 2139 久违的月赛之二
查看>>
xcode 8 去除无用打印信息
查看>>