Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Android Styleable Custom View

Android Styleable Custom View

Slides to go along with a presentation on making custom Android views styleable through xml attributes.

Joe Rowley

July 18, 2016
Tweet

More Decks by Joe Rowley

Other Decks in Programming

Transcript

  1. The Challenge • The design team has established a strong

    design and theme for the app. • Even though design elements keep the same or similar form, there are variations to communicate state or to differentiate sections of the app.
  2. Step One: Custom View • Extend a base View class

    – Most often one of the layouts: LinearLayout, FrameLayout, RelativeLayout • Build your xml layout • Remember to change the root to merge when you have it all set • Create initView method (or similar) and call from all constructors to inflate the layout • Expose needed methods in the Javas just like any other
  3. Step Two: Make it Styleable • Declare the View styleable

    in attrs.xml • Define each attribute for the view • Define the format(s) for each attribute • Optionally, define flags for specific, limited possible values
  4. Step Three: Consume the Attributes • Inside initView, after inflating

    the layout, retrieve the attributes • TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ComplexEditText); • Attributes may not be present • Some attributes may be represented in different formats • Don't forget to recycle the TypedArray
  5. Step Four: Wire it all together • Declare a namespace

    pointing to res-auto • xmlns:app="http://schemas.android.com/apk/res­auto" • Apply your attributes as you would any others, but prefixed with your own namespace
  6. Tips • Look through the Android source code, especially for

    the view that you're extending or views that you're incorporating • http://trickyandroid.com/protip-inflating-layout-for-your- custom-view/