xmlns的作用

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,这样代码中会关联这个,以免使用了不必要的属性

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容