View on GitHub

Bearded-android-docs

CustomView

Download this project as a .zip file Download this project as a tar.gz file

Created Sunday 10 November 2013

To control the view with XML:

Defining Custom XML Attributes

@Example (res/values/attrs.xml file)
<resources>
   <declare-styleable name="PieChart">
       <attr name="showText" format="boolean" />
       <attr name="labelPosition" format="enum">
           <enum name="left" value="0"/>
           <enum name="right" value="1"/>
       </attr>
   </declare-styleable>
</resources>

Using Custom XML Attributes

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:custom="http://schemas.android.com/apk/res/[yourpackagename]">
 <com.example.customviews.charting.PieChart
     custom:showText="true"
     custom:labelPosition="left" />
</LinearLayout>

Note: You can use any namespace instead of custom.

Setting Custom XML Attributes in the View

public PieChart(Context context, AttributeSet attrs) {
   super(context, attrs);
   

TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.PieChart,
0, 0);

try {
mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
} finally {
a.recycle();
}
}

Note: use #obtainStyledAttributes to get a TypedArray. Make sure to call #recycle when you're done.

Layout


No backlinks to this page.
comments powered by Disqus