码迷,mamicode.com
首页 > 移动开发 > 详细

如何在android style文件中使用自定义属性

时间:2014-11-24 12:01:43      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:exception   android   

      前几天我在项目中遇到了这样一个问题:我为项目编写了一个自定义控件,这个控件会被大量复用,所以我准备在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中开始使用自定义属性,如下:

<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中使用命名控件的地方换成自定义控件的包名即可(注意:是包名,不带自定义控件的名字),如下:

<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文件中使用自定义属性了。


参考链接:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=316876

如何在android style文件中使用自定义属性

标签:exception   android   

原文地址:http://blog.csdn.net/zhufuing/article/details/41395219

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!