android:layout_width and android:layout_height are required attributes, i.e. if you don't specify them for a Layout, Android Studio tells me "Element x doesn't have required attribute android:layout_height."
I'm defining some custom attributes in my own classes and I'd like to require that anyone who uses them in xml specify values just like they have to specify layout_width and layout_height.
How do I do that? Is there something I can add in attrs.xml here:
<declare-styleable name="MyStyleable">
<attr name="myAttribute" format="float"/>
</declare-styleable>
Or maybe in style.xml here:
<style name="MyStyle">
<item name="myAttribute">3</item>
</style>
AFAIK, currently attr
s don't have any attributes to mark them mandatory. ("layout_width"
and the like are very common mistakes, checking for those is wired into the SDK)
You can, however, throw an RuntimeException
from your custom View
if an attribute is missing (which you can determine by calling TypedArray.hasValue()
) -- TypedArray
does that in getLayoutDimension()
method.
This is exactly the behavior you get if you compile an app that's missing a "layout_width"
somewhere using command line tools (i.e. no Eclipse or Idea to detect the missing atrribute and prevent you from compiling): you run the app and it crashes immediately with a RuntimeException
saying you're missing the attribute.
Using Android KTX, there are extension functions that provide getFloatOrThrow()
and other similar methods.
Check them out here
TypedArray also has a few methods to cover both attribute getting and exception throwing states. Just use them if you want your attribute to be required (not clearly)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With