23.07.2015 Views

Android Tutorial

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

custom:delimiter="-"<br />

custom:fancyText="true"<br />

/><br />

STEP 1<br />

The first step to enable us to use our custom attributes is to define them in a new xml file underres/values/ and call<br />

it attrs.xml. Let's have a look on an example attrs.xml file:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Here the name=value is what we want to use in our Layout XML file as attribute, and the format=type is the type<br />

of attribute.<br />

STEP 2<br />

Your second step will be to read these attributes from Layout XML file and set them for the component. This logic<br />

will go in the constructors that get passed an AttributeSet, since that is what contains the XML attributes. To read<br />

the values in the XML, you need to first create a TypedArray from theAttributeSet, then use that to read and set the<br />

values as shown in the below example code:<br />

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView);<br />

final int N = a.getIndexCount();<br />

for (int i = 0; i < N; ++i)<br />

{<br />

int attr = a.getIndex(i);<br />

switch (attr)<br />

{<br />

case R.styleable.DateView_delimiter:<br />

String delimiter = a.getString(attr);<br />

//...do something with delimiter...<br />

break;<br />

case R.styleable.DateView_fancyText:<br />

boolean fancyText = a.getBoolean(attr, false);<br />

TUTORIALS POINT<br />

Simply Easy Learning

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!