Did you know: Reusing native element attributes in Custom Views

It’s interesting some of the little things you could take for granted and figure out while digging in the Android source code.  If you’ve ever created your own custom views in Android you’ll note that sometimes you might require to make your own custom element attributes to style the appearance of your view when its defined in an XML file/element. Did you know though that instead of recreating some common attribute you could reuse the built-in defined element attributes?

Instead of:

<resources>
   <declare-styleable name="MyAwesomeLabelView">
       <attr name="malv_text" format="string|reference"/>
       <attr name="malv_icon" format="reference"/>
   </declare-styleable>
</resources>

you could :

<resources>
   <declare-styleable name="MyAwesomeLabelView">
      <attr name="android:text" />
      <attr name="android:icon" />
   </declare-styleable>
</resources>

Pretty cool huh!?  Just don’t get carried away with this by “overriding” all the native attributes in your custom views styleable declaration.

Did you know: ContextCompat

Lately I’ve been refactoring some old code and one of the common issues I found was about deprecated calls to methods in the Resources class. I use the getDrawable(int) and getColor(int) calls in a lot of places . The suggestion from lint is that I use the matching method calls with an extra Theme parameter for styling purposes.

If you’d rather have the system handle that extra parameters for you, then maybe ContextCompat is for you. ContextCompat will provide a theme styled for the specified Context’s theme.

Instead of:

<activity>.getResources().getColor(R.color.levelColor)

you would:

ContextCompat.getColor(<context>,R.color.levelColor);

The same applies for most of the deprecated methods in Resources like getColorStateList. Check out ContextCompat.