内容简介:怎么使用系统已经定死没有什么好挣扎的,按照步骤一步一步来即可。我们为上节定义的 View 添加一个颜色属性,改变绘制的圆圈的颜色。新建 attr.xml 文档,并定义属性。
怎么使用系统已经定死没有什么好挣扎的,按照步骤一步一步来即可。
-
在
res/values文件夹下创建 attr.xml 文件。 -
在
attr.xml文件中创建declare-styleable节点,并定义name属性。name 属性为自定义view类名。
-
然后就可以在
declare-styleable节点中定义attr节点定义属性了,attr 节点有两个属性- name : 在布局中使用该属性的名字。
-
format : 属性的类型,一共有 10 种。
- boolean : 布尔类型
- color:颜色类型,可以是16进制表示也可以是@color表示
- dimension:表示 attr 取值是尺寸类型,例如16sp,16dp,也可以是一个@dimen类型
- float: 表示 attr 取值类型是整型或浮点型
- integer:表示attr取值类型是整型
- fraction:表是attr取值是百分之数类型,只能以%结尾。
- string:表示 string 类型,或者指向 String 资源的 id。
- refrerence 表示 attr 取值只能是指向一个资源的id。
- enum 表示 attr 取值只能是枚举类型。
- flag 表示 attr 取值是 flag 类型.
-
最后在自定义 view 的构造方法中获取自定义属性并进行解析。
使用
我们为上节定义的 View 添加一个颜色属性,改变绘制的圆圈的颜色。
step 1
新建 attr.xml 文档,并定义属性。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FreeStyleView">
<attr name="color" format="color"></attr>
</declare-styleable>
</resources>
复制代码
step 2
在自定义 View 中处理自定义属性。
这里将之前写的 init()
方法稍作改造。
public FreeStyleView(Context context) {
super(context);
init(context,null);
}
public FreeStyleView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public FreeStyleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs) {
// 用代码新建的没有xml定义的属性
if (attrs != null){
// 处理属性(Android系统自带的属性我们不用定义即可使用,but还是要处理的)
// 这一步是解析属性,因为不这样操作通过循环我们也能拿到属性名字以及对应的值,但适配、以及获取资源不太易操作。
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.FreeStyleView);
// 获取颜色,第一个参数是在 attr 定义的属性,系统做了处理,名称变成了FreeStyleView_color,
// 第二个参数是默认值
color = typedArray.getColor(R.styleable.FreeStyleView_color,color);
}
paint = new Paint();
// 设置画笔模式,FILL 填充,STROKE 描边
paint.setStyle(Paint.Style.STROKE);
// 设置画笔颜色
paint.setColor(color);
// 设置画笔宽度,px 为单位,实际需要转换成 dp 值
paint.setStrokeWidth(8);
}
复制代码
step 3
最后在布局文件中使用自定义的属性
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.myapplication.view.FreeStyleView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:color="#eeff16"/>
</RelativeLayout>
复制代码
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
算法艺术与信息学竞赛
刘汝佳 / 清华大学出版社 / 2004-1 / 45.00元
《算法艺术与信息学竞赛》较为系统和全面地介绍了算法学最基本的知识。这些知识和技巧既是高等院校“算法与数据结构”课程的主要内容,也是国际青少年信息学奥林匹克(IOI)竞赛和ACM/ICPC国际大学生程序设计竞赛中所需要的。书中分析了相当数量的问题。 本书共3章。第1章介绍算法与数据结构;第2章介绍数学知识和方法;第3章介绍计算机几何。全书内容丰富,分析透彻,启发性强,既适合读者自学,也适合于课......一起来看看 《算法艺术与信息学竞赛》 这本书的介绍吧!