Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required custom attributes

Tags:

android

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>
like image 866
Mike Miller Avatar asked May 14 '14 20:05

Mike Miller


3 Answers

AFAIK, currently attrs 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.

like image 101
Ivan Bartsov Avatar answered Nov 04 '22 10:11

Ivan Bartsov


Using Android KTX, there are extension functions that provide getFloatOrThrow() and other similar methods.

Check them out here

like image 30
William Reed Avatar answered Nov 04 '22 11:11

William Reed


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)

enter image description here

like image 1
Shvedkov Ivan Avatar answered Nov 04 '22 10:11

Shvedkov Ivan