您的位置:首页 > 移动开发 > Android开发

Android 自定义View 属性和命名空间

2016-05-05 15:27 531 查看

Android 自定义View 的属性

例如我们创建了一个自定义的MultiSwipeRefreshLayout。要给它添加一个背景。可以是一个引用。

在res/values/attrs.xml 文件中创建 自定义属性和与其对应的style。

格式如下:

<resources>

<declare-styleable name="MultiSwipeRefreshLayout">
<attr name="foreground"
format="reference"/>
</declare-styleable>

</resources>


这样我们就定义了 一个属性 foreground, 和与其对应的Style “MultiSwipeRefreshLayout”。

在布局文件中使用,

<me.drakeet.meizhi.widget.MultiSwipeRefreshLayout     app:foreground="@drawable/abc_cab_background_internal_bg"
android:layout_width="match_parent"
android:layout_height="match_parent">


自定义View 是如何获取 对应的属性的。肯定是通过XML 解析。

猜测一下,当xml 通过布局文件创建一个MultiSwipeRefreshLayout对象时,会解析MultiSwipeRefreshLayout 节点下的各各属性。然后会根据属性名找到对应的style,然后根据style 进行分组。然后传递给MultiSwipeRefreshLayout 的构造函数。

public MultiSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MultiSwipeRefreshLayout, 0, 0);
mForegroundDrawable = a.getDrawable(
R.styleable.MultiSwipeRefreshLayout_foreground);
if (mForegroundDrawable != null) {
mForegroundDrawable.setCallback(this);
setWillNotDraw(false);
}
a.recycle();
}


可以看到 TypedArray a 是通过对应的 R.styleable.MultiSwipeRefreshLayout 获取的。

属性名称冲突问题。

我们定义的每个属性名都是独一无二的,这样才能根据属性名找到对应的style。如果命名重复:

<declare-styleable name="MultiSwipeRefreshLayout">
<attr name="foreground"
format="reference"/>
</declare-styleable>
<declare-styleable name="Same">
<attr name="foreground"
format="reference"/>
</declare-styleable>


编译不会通过:

Error:Error: Found item Attr/foreground more than one time

关于命名空间

w3c 中的定义:

XML Namespace (xmlns) 属性

XML 命名空间属性被放置于元素的开始标签之中,并使用以下的语法:

xmlns:namespace-prefix=”namespaceURI”

当命名空间被定义在元素的开始标签中时,所有带有相同前缀的子元素都会与同一个命名空间相关联。

注释:用于标示命名空间的地址不会被解析器用于查找信息。其惟一的作用是赋予命名空间一个惟一的名称。不过,很多公司常常会作为指针来使用命名空间指向实际存在的网页,这个网页包含关于命名空间的信息。

猜测,对于不同的命名空间,android 的xml 解释器会做不同的处理。

xmlns:android=”http://schemas.android.com/apk/res/android”

这个命名空间的属性是在系统的attrs.xml 文件中定义的。



xmlns:app=”http://schemas.android.com/apk/res-auto”

使用自定义view 或者lib 包中 定义 的view(也算自定义View)。

Material 提供的各种新View 控件定义了一些新的属性。

FloatingActionButton

<android.support.design.widget.FloatingActionButton
android:id="@+id/main_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/fab_margin_bottom"
android:layout_marginRight="@dimen/fab_margin_right"
android:layout_gravity="right|bottom"
android:clickable="true"
android:elevation="4dp"
app:elevation="4dp"
app:layout_anchor="@id/swipe_refresh_layout"
app:borderWidth="0dp"
app:layout_anchorGravity="right|bottom"


这些新的属性使用前,要加上

<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"   xmlns:android="http://schemas.android.com/apk/res/android"


命名空间重要的是后面的URL ,前缀随便起,可以把android,app 。替换成什么都行。不过大家一般都会写成这两个。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android