自定义View --- 自定义属性

【记录】记录点滴

【场景】写自定义View时,如果希望View可以支持多种样式,比如圆角ImageView可以设置圆角弧度,就需要实现自定义属性。不常写的东西容易忘。

1. /res/values/attrs.xml文件中定义属性

先附上示例代码

<!-- declare-styleable表明一个属性组,CustomView是自定义View的类名 -->
<declare-styleable name="CustomView">
        <!-- 定义一个属性,使用枚举方式 -->
        <attr name="attr1_mode">
            <enum name="mode_one" value="0"/>
            <enum name="mode_two" value="1"/>
        </attr>
        <!-- 定义一个接收String类型的属性 -->
        <attr name="attr2" format="string"/>
</declare-styleable>

2. 属性类型format

<attr>元素中 format指明了属性的类型,以常用控件为例。对于如何在自定义View中添加自定义属性,可以查看5)enum枚举类型

1) reference,如

<!-- attrs.xml定义 -->
<attr name = "background" format = "reference" />
<!-- layout.xml使用 -->
<ImageView android:background = "@drawable/drawable_id"/>

2)  color,如

<!-- attrs.xml定义 -->
<attr name = "textColor" format = "color" />
<!-- layout.xml使用 -->
<TextView android:textColor = "#00FF00" />

 3) boolean,如

<!-- attrs.xml定义 -->
<attr name = "focusable" format = "boolean" />
<!-- layout.xml使用 -->
<Button android:focusable = "true"/>

4) dimension,如

<!-- attrs.xml定义 -->
<attr name = "layout_width" format = "dimension" />
<!-- layout.xml使用 -->
<Button android:layout_width = "42dp"/>

5)enum枚举,这里顺带写上,如何在自定义View中添加自定义属性的用法

<!-- 对于CustomView,在attrs.xml定义 -->
<attr name="attr1_mode">
      <enum name="mode_one" value="0"/>
      <enum name="mode_two" value="1"/>
</attr>
<!-- layout.xml使用CustomView -->
<!-- 命名空间 custom,可以根据喜好命名,例如我们可能常用就是默认的app(使用时app:xxx),引入有两种方式 -->
<!-- 方式1:xmlns:custom="http://schemas.android.com/apk/res-auto” -->
<!-- 方式2:xmlns:custom="http://schemas.android.com/apk/our_app_packagename"-->
<CustomView custom:attr1_mode="mode_one"/>

6)flag位或

<!-- attrs.xml中定义 -->
<attr name="gravity">
       <flag name="top" value="0x30" />
       <flag name="bottom" value="0x50" />
       <flag name="left" value="0x03" />
       <flag name="right" value="0x05" />
       <flag name="center_vertical" value="0x10" />
</attr>
<!-- layout.xml中使用 -->
<TextView android:gravity="bottom|left"/>

7)混合类型

<!-- attrs.xml中定义 -->
<attr name = "background" format = "reference|color" />

<!-- layout.xml中使用 -->
<ImageView android:background = "@drawable/drawable_id" />
或者:
<ImageView android:background = "#00FF00" />

8)fraction

<!-- attrs.xml中定义 -->
<attr name = "pivotX" format = "fraction" />
<!-- 像anim.xml中使用 -->
<rotate android:pivotX = "50%"/>

9) 其他类型,float,integer,string

3. 在Java代码中获取对应的属性

利用TypedArray获得自定义属性

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, defStyleAttr, 0);
//enum类型的mode,假设DEFAULT_MODE=0,对应mode_one
int mode= a.getInt(R.styleable.CustomView_attr1_mode, DEFAULT_MODE);
String attr2= a.getString(R.styleable.CustomView_attr2);
//这里,用完要记得回收
a.recycle();

获取到自定义属性后,就可以绘制对应的内容了。

参考 https://www.cnblogs.com/wjtaigwh/p/6594680.html

猜你喜欢

转载自blog.csdn.net/FeiLaughing/article/details/83375741