如何在android style文件中使用自定义属性
2016-05-04 21:01
721 查看
前几天我在项目中遇到了这样一个问题:我为项目编写了一个自定义控件,这个控件会被大量复用,所以我准备在style.xml文件中定义一个style来减少重复xml布局内容的编写,但是里面有一个自定义的控件属性,问题出现在这里,虽然自定义属性在layout布局xml中可以使用正常,但是却无法在style中定义,本来这个控件是大量服用的,style也是为了复用减少xml内容写的,我可以把自定义属性内容直接写死在自定义控件中,但是考虑到项目未来可能出现的变数,我还是准备将这个自定义属性写到style中,这样即便有其他不同样式的复用,我也只需再写一个style即可。
在layout布局中使用自定义属性是非常简单,我们只需要在xml根节点xmlns:Android="http://schemas.android.com/apk/res/android" 的后面加上我们自定义控件的命名空间(栗子:xmlns:test="http://schemas.android.com/apk/res/packagename),然后就可以在自定义控件节点里自由使用自定义属性了。
我在编写style的时候,起初也以为style.xml也应该是这种使用方式,于是就在根节点添加了自定义控件的命名空间,然后就在style中开始使用自定义属性,如下:
[html] view
plain copy
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/res/com.zhufuing" >
<style name="test" >
<item name="test:name_text">hello,world!</item>
</style>
</resources>
但是这样并不起作用,style.xml反而出现错误,报错提示如下:
error: Error: No resource found that matches the given name: attr 'test:name_text'.
我在网上搜索之后得到了正确的答案,其实我们在style.xml中使用自定义属性的话,不需要写自定义控件的命名空间,我们只需要在style中使用命名控件的地方换成自定义控件的包名即可(注意:是包名,不带自定义控件的名字),如下:
[html] view
plain copy
<resources xmlns:android="http://schemas.android.com/apk/res/android" >
<style name="test" >
<item name="com.zhufuing:name_text">hello,world!</item>
</style>
</resources>
这样就可以在style文件中使用自定义属性了。
在layout布局中使用自定义属性是非常简单,我们只需要在xml根节点xmlns:Android="http://schemas.android.com/apk/res/android" 的后面加上我们自定义控件的命名空间(栗子:xmlns:test="http://schemas.android.com/apk/res/packagename),然后就可以在自定义控件节点里自由使用自定义属性了。
我在编写style的时候,起初也以为style.xml也应该是这种使用方式,于是就在根节点添加了自定义控件的命名空间,然后就在style中开始使用自定义属性,如下:
[html] view
plain copy
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/res/com.zhufuing" >
<style name="test" >
<item name="test:name_text">hello,world!</item>
</style>
</resources>
但是这样并不起作用,style.xml反而出现错误,报错提示如下:
error: Error: No resource found that matches the given name: attr 'test:name_text'.
我在网上搜索之后得到了正确的答案,其实我们在style.xml中使用自定义属性的话,不需要写自定义控件的命名空间,我们只需要在style中使用命名控件的地方换成自定义控件的包名即可(注意:是包名,不带自定义控件的名字),如下:
[html] view
plain copy
<resources xmlns:android="http://schemas.android.com/apk/res/android" >
<style name="test" >
<item name="com.zhufuing:name_text">hello,world!</item>
</style>
</resources>
这样就可以在style文件中使用自定义属性了。
相关文章推荐
- 安卓实现QQ侧滑菜单效果
- android studio gradle下载失败解决方案
- Android基础 | 意图Intent讲解
- Android 内功心法(1.2)——android常用设计模式之工厂模式
- 解决No resource found that matches the given name 'android:Theme.Material.Light.DarkActionBar'
- Android 触摸事件机制(二) Activity中触摸事件详解
- Android基础 | 创建新的Activity
- Android MVP模式
- Android 沿着线绘制文字
- Android中Base64的简单使用
- Android Dev Intro - Android SurfaceTexture
- Android Dev Intro - SurfaceTexture,TextureView, SurfaceView and GLSurfaceView
- Android Dev Intro - Android Thread Intro
- Android:使用MuPdf开源库阅读PDF文件
- Android剪切板传递数据传递序列化对象数据
- 【流媒体】 Android 实时视频编码—H.264硬编码
- Android 内功心法(1.1)——android常用设计模式之单例模式
- Android_EventBus的使用
- android布局属性详解
- Android插件化开发笔记(一)