美文网首页
xmlns的作用

xmlns的作用

作者: popli | 来源:发表于2017-11-13 15:27 被阅读33次

    xml中可以有同名元素<element>,为了区分,我们加入命名空间的概念
    我们指定命名空间: xmlns:tools="http://schemas.android.com/tools"
    和xmlns:android="http://schemas.android.com/apk/res-auto"
    这样我们
    <TextView
    android:text=“真正显示”
    tools:text="设计时显示"/>

    当我们的xml parser 解析的时候会取字段,Android的命名规则就是
    xmlns:android="http://schemas.android.com/apk/res/你app的包名"
    这样这个属性就是唯一标识的
    我们通过命名空间来确定唯一的属性

    在value/attrs.xml
    里面定义
    <declare-styleable name="xxx">
    <attr name="attr_xxx" format ="String">
    </declare-styleable>

    在xml中就可以指定这个包的命名空间,这样ide就会自动关联,这样我们就不用看代码去知道有哪些合法的属性了
    然后我们在代码中
    TypedArray a = context.obtainStyledAttributes(AttributeSet, R.styleable.xxx,0 );
    str = a.getString(R.styleable.attr_xxx);

    其实只要我们在attrs.xml中定义的属性每个元素都能使用,但是为了区分,加入了declare-styleable,这样代码中会关联这个,以免使用了不必要的属性

    相关文章

      网友评论

          本文标题:xmlns的作用

          本文链接:https://www.haomeiwen.com/subject/rijzmxtx.html