declare styleable property reuse scheme for custom controls in Android
- 2020-06-12 10:34:41
- OfStack
Recently contacted Android custom controls, involving in the custom xml attributes (attribute), actually is also very simple, but, I write this found that code is not perfect, is in attrs. xml the file, find attribute redundancy, so I want to have a similar property inheritance or include method. This article will discuss declare - stylable attributes reuse record 1.
Imperfect code
<?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>
As shown in the above code, ExTextView and ExEditText have repeated attribute declarations in stylable. Although the above works, it always feels unprofessional, so I look for optimization methods.
Is that ok
Try specifying 1 parent for ES23en-ES24en, as follows
<?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 did not report a syntax error. But when I used R.styleable.ExEditText_supportDeviceType, the R file was not generated, the project was cleaned up again and did not take effect. I do not know if it is an adt plug-in or not.
The ultimate answer
In fact, we can declare the property to be used multiple times before ES42en-ES43en, just by calling it inside the ES44en-ES45en node, as shown below.
<?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>
After each reference to attr, it is recommended to clean up 1 project to ensure that the R file is rebuilt.
read
http://stackoverflow.com/questions/18827875/how-to-declare-several-stylable-attributes-with-the-same-name-for-different-tags