前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自定义控件进阶:declare-styleable重用attr

自定义控件进阶:declare-styleable重用attr

作者头像
技术小黑屋
发布2018-09-04 16:45:17
1.6K0
发布2018-09-04 16:45:17
举报
文章被收录于专栏:技术小黑屋技术小黑屋

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

不完美的代码

1 2 3 4 5 6 7 8 9 10 11 12 13

<?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,如下代码

1 2 3 4 5 6 7 8 9 10 11 12

<?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节点内部,只需调用即可.具体代码如下.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

<?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文件重新生成.

延伸阅读

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 不完美的代码
  • 这样可以么
  • 终极答案
  • 延伸阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档