4. Attachment/Detachment
o
nAttached
ToWindow
()
● Perform any relevant state resets
● Start listening for state changes
● Remove any posted Runnables
● Stop listening for data changes
● Clean up resources
■ Bitmaps
■ Threads
onDetachedFrom
Window()
6. State save/recover
public class CustomView extends View {
private int stateToSave;
...
static class SavedState extends BaseSavedState {
int stateToSave;
SavedState(Parcelable superState) {
super(superState);
@Override
public
Parcelable onSaveInstanceState()
}
{
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.stateToSave = this.stateToSave;
return ss;
private SavedState(Parcel in) {
super(in);
this.stateToSave = in.readInt();
}
}
@Override
public void writeToParcel(Parcel out, int flags) {
@Override
super.writeToParcel(out, flags);
public void onRestoreInstanceState(Parcelable state) {
out.writeInt(this.stateToSave);
}
if(!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
}
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
this.stateToSave = ss.stateToSave;
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
}
};
}
}
7. Creating a new view
●
●
●
●
●
Subclass View or ViewGroup.
○ Use SurfaceView in case of 3D graphics.
Define custom attributes.
○ Use <declare-styleable> resource element.
Apply custom attributes.
○ Use AttributeSet as an argument of the constructor and pass it to obtainStyledAttributes().
Add properties and events.
○ At this step usually we call invalidate() and requestLayout().
Override traversal methods.
○ Override onMeasure(), onLayout(), onDraw().
10. Tips & tricks
●
●
●
●
onMeasure()
○
Determines a size for the view and its children.
○
Must call setMeasuredDimension() before returning, otherwise an IllegalStateException exception will be
thrown..
onLayout()
○
Use getMeasuredWidth()/getMeasuredHeight().
○
getWidth()/getHeight() become valid on a view after layout() returns.
Use invalidate(int, int, int, int) to avoid drawing areas that will remain the same.
onDraw()
○
Draws the content, e.g. text in TextView.
○
The background is drawn before onDraw().
○
Skipped if setWillNotDraw(true) is set (default in ViewGroup).
○
Use hardware rendering (Android 3.0 +) which calles draw() only on the invalidate() source view and not
its parents.