android开发分享Android中自定义控件的declare-styleable属性重用方案

最近接触了android自定义控件,涉及到自定义xml中得属性(attribute),其实也很简单,但是写着写着,发现代码不完美了,就是在attrs.xml这个文件中,发现

最近接触了android自定义控件,涉及到自定义xml中得属性(attribute),其实也很简单,但是写着写着,发现代码不完美了,就是在attrs.xml这个文件中,发现属性冗余,于是就想有没有类似属性继承或者include之类的方法.android开发分享Android中自定义控件的declare-styleable属性重用方案将就declare-stylable中属性重用记录一下.

上述就是android开发分享Android中自定义控件的declare-styleable属性重用方案的全部内容,如果对大家有所用处且需要了解更多关于Android学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

不完美的代码

复制代码 代码如下:
<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
 
    <declare-styleable name=”extextview”>
       <attr name=”enableonpad” format=”boolean” />
     <attr name=”supportdevicetype” format=”reference”/>
    </declare-styleable>

    <declare-styleable name=”exedittext”>
       <attr name=”enableonpad” format=”boolean” />
     <attr name=”supportdevicetype” format=”reference”/> 
    </declare-styleable>
</resources>

如上面代码,在extextview和exedittext这个stylable中有着重复的属性申明.虽然上面可以工作,但是总感觉写的不专业,于是寻找优化方法.

这样可以么

尝试着为declare-stylable指定一个parent,如下代码

复制代码 代码如下:
<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
 
    <declare-styleable name=”extextview”>
       <attr name=”enableonpad” format=”boolean” />
     <attr name=”supportdevicetype” format=”reference”/>
    </declare-styleable>

    <declare-styleable name=”exedittext” parent=”extextview”>
         
    </declare-styleable>
</resources>

attrs.xml没有报告语法错误.但是当我使用r.styleable.exedittext_supportdevicetype时候,r文件却没有生成,重新清理了工程还是不生效,不知道是否为adt插件的问题.其他人也遇到了这样的问题. 这个方法目前是不行的.

终极答案

实际上我们可以在declare-stylable之前,申明要多次使用的属性,在declare-stylable节点内部,只需调用即可.具体代码如下.

复制代码 代码如下:
<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
  <attr name=”enableonpad” format=”boolean” />
  <attr name=”supportdevicetype” format=”reference”/>
 
    <declare-styleable name=”extextview”>
        <attr name=”enableonpad”/>
        <attr name=”supportdevicetype”/>
    </declare-styleable>

    <declare-styleable name=”exedittext”>
        <attr name=”enableonpad”/>
      <attr name=”supportdevicetype”/>
    </declare-styleable>
</resources>

每次引用attr后,建议清理一下工程,确保r文件重新生成.

延伸阅读

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/addevelopment/940693.html

(0)
上一篇 2021年11月13日
下一篇 2021年11月13日

精彩推荐