你好,游客 登录 注册 搜索
背景:
阅读新闻

Android自定义属性时TypedArray的使用方法

[日期:2013-04-16] 来源:Linux社区  作者:eyu8874521 [字体:大 中 小]

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相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       Android自定义属性  TypedArray 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款