Styles are not appliedInstead, passAttributeSetToobtainStyledAttributes(). This method passes backTypedArrayArray of values that have already been dereferenced and styled.
The Android resource compiler does a lot of work for you to make callingobtainStyledAttributes()Easier. For each Resource in the res directory, the generated R. java defines both an array of attribute ids and a set of constants that define the index for each attribute in the array. you use the predefined constants to read the attributes fromTypedArray. Here's howPieChartClass reads its attributes:
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 thatTypedArrayObjects are a shared resource and must be recycled after use.
4. Add Properties and EventsAttributes are a powerful way of controlling the behavior and appearance of views, but they can only be read when the view is initialized. to provide dynamic behavior, expose a property getter and setter pair for each custom attribute. the following snippet shows howPieChartExposes a property calledshowText:
public boolean isShowText() { return mShowText;}public void setShowText(boolean showText) { mShowText = showText; invalidate(); requestLayout();}
Notice thatsetShowTextCILSinvalidate()AndrequestLayout(). These CILS are crucial to ensure that the view behaves reliably. you have to invalidate the view after any change to its properties that might change its appearance, so that the system knows that it needs to be redrawn. likewise, you need to request a new layout if a property changes that might affect the size or shape of the view. forgetting these method CILS can cause hard-to-find bugs.
Custom views shoshould also support event listeners to communicate important events. For instance,PieChartExposes a custom event calledOnCurrentItemChangedTo define y listeners that the user has rotated the pie chart to focus on a new pie slice.
It's easy to forget to expose properties and events, especially when you're the only user of the custom view. taking some time to carefully define your view's interface CES future maintenance costs. A good rule to follow is to always expose any property that affects the visible appearance or behavior of your custom view.
V. Design For AccessibilityYour custom view shocould support the widest range of users. This includes des users with disabilities that prevent them from seeing or using a touchscreen. To support users with disabilities, you shoshould:
- Label your input fields using
android:contentDescriptionAttribute
- Send accessibility events by calling
sendAccessibilityEvent()When appropriate.
- Support alternate controllers, such as D-pad and trackball