自定义View(1)——构造方法与参数传递
来源:互联网 发布:酷家乐咋装修设计软件 编辑:程序博客网 时间:2024/06/09 18:32
在自定义View的过程中,最先需要了解View的四种构造方法的使用条件以及参数。
四种构造方法如下:
/** * 使用代码 new 创建时使用 */ public StatusBar(Context context) { this(context, null); } /** * 使用布局文件加载时使用 * @param context * @param attrs 布局文件参数 */ public StatusBar(Context context, AttributeSet attrs) { this(context, attrs, 0);// this(context, attrs, R.style.Base_Theme_AppCompat_Light); // 显示的调用构造方法 } /** * 使用默认style 只有明确调用时才生效 * @param context * @param attrs 布局文件参数 * @param defStyleAttr activity 或 application 的风格 */ public StatusBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // 初始化控件 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusBar); typedArray.recycle(); init(); } /** * 最小 API21 使用 目前没有实际用途 * @param context * @param attrs * @param defStyleAttr * @param defStyleRes */ public StatusBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context); }</span>
首先需要在 res/values/attrs.xml 文件中如下配置:
<declare-styleable name="StatusBar"> <attr name="type" format="string" /> <attr name="greenColor" format="color" /> <attr name="grayColor" format="color" /> <attr name="textGreenColor" format="color" /> <attr name="textGrayColor" format="color" /> <attr name="textSize" format="integer"/> </declare-styleable></span>使用 declare-styleable 声明风格,使用attr 来声明具体的参数。
xml中需要使用自定义View的属性,需要声明命名空间,然后直接使用属性:
xmlns:app="http://schemas.android.com/apk/res-auto"
<com.example.administrator.mydemo.widget.StatusBar android:id="@+id/bar" app:textSize="14" app:textGreenColor="#fff000" android:layout_width="match_parent" android:layout_height="wrap_content" /></span>在构造方法代码中接收传递的参数:
public StatusBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // 初始化控件 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusBar); this.textsize = typedArray.getInteger(R.styleable.StatusBar_textSize,14); this.finishTextColor = typedArray.getColor(R.styleable.StatusBar_textGreenColor,Color.RED); // 释放资源 typedArray.recycle(); init(); }
通过参数Attributes将传递的参数一一解析,最后不要忘了释放TypeArray资源。
最后跟上这个Demo的GitHub地址:GitHub简单自定义View Demo地址
0 0
- 自定义View(1)——构造方法与参数传递
- 构造方法与参数传递
- 自定义view构造方法
- Android自定义View传递参数
- 自定义View的构造方法
- 自定义view之构造方法
- 自定义view的构造方法
- 面向对象 参数传递 (方法 -- 构造方法--重载)
- 自定义View构造函数参数理解
- 自定义View时,构造参数的调用
- 自定义view-构造方法和自定义属性
- C++学习笔记(6)——多重继承类对象的构造函数参数的传递方法
- 构造方法和参数传递总结
- Android中自定义样式与View的构造函数中的第三个参数defStyle的意义
- Android中自定义样式与View的构造函数中的第三个参数defStyle的意义
- Android中自定义样式与View的构造函数中的第三个参数defStyle的意义
- Android中自定义样式与View的构造函数中的第三个参数defStyle的意义
- Android中自定义样式与View的构造函数中的第三个参数defStyle的意义
- Json.stringify()的用法
- Linux中的文件描述符与打开文件之间的关系
- 一、android XML资源文件详解 —— 从物理上分析
- 再谈sizeof
- 数据结构=C++语言=队列==顺序存储实现
- 自定义View(1)——构造方法与参数传递
- codeforces 180C Letter
- 浅谈cookie和session的关系
- 不确定性学习(1)
- Go语言程序设计:集合类型
- 中山大学(大三感想)
- BP神经网络的matlab实现
- 几道经典算法题
- 多线程之间及多进程间的通信