要在Android中为视图创建自定义属性,需要在项目的res/values
目录中的attrs.xml
文件中声明自定义属性。以下是如何在attrs.xml
中为视图定义自定义属性的示例:
<resources>
<declare-styleable name="CustomView">
<attr name="customAttribute" format="string"/>
</declare-styleable>
</resources>
在本例中,我们为CustomView
视图定义了一个名为customAttribute
的自定义属性
。format
属性指定自定义属性的数据类型,可以是字符串或者int或者颜色值等。在这种情况下,它被定义为一个字符串。
- reference - 如果需要引用其他资源 (如:
"@color/my_color"
,"@layout/my_layout"
) - color
- boolean
- dimension
- float
- integer
- string
- fraction
- enum - 通常隐式的定义
- flag - 通常隐式的定义
你可以通过|
设置多个格式 , 如:format="reference|color"
enum 可以用如下方式定义:
<attr name="my_enum_attr">
<enum name="value1" value="1" />
<enum name="value2" value="2" />
</attr>
flag 是相似的,只是需要定义值,以便将它们位存储在一起:
<attr name="my_flag_attr">
<flag name="fuzzy" value="0x01" />
<flag name="cold" value="0x02" />
</attr>
一旦在attrs.xml
中定义了自定义属性,就可以像其他任何属性一样在自定义视图的布局xml
文件中使用它。以下是如何使用它的示例:
<com.example.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customAttribute="Hello, world!" />
在此示例中,我们将 customAttribute
属性的值设置为“Hello, world!”对于我们的 CustomView 视图。请注意,我们使用 app:
命名空间来引用我们的自定义属性
最后,通常在自定义视图的构造函数里访问自定义属性,如下:
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView, defStyle, 0);
// R.styleable.CustomView_customAttribute 引用指向的是要访问的自定义属性的资源id
String str = a.getString(R.styleable.CustomView_customAttribute);
//do something with str
a.recycle();
}
可能还需要把引用空间:
xmlns:whatever=“http://schemas.android.com/apk/res-auto”
替换成:
xmlns:whatever=“http://schemas.android.com/apk/res/org.example.mypackage”
whatever 可能是android,app或者tools