SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
Android Custom
Views
Christoforos Nalmpantis
Why custom views
1. Unique UX.
2. Optimised performance.
3. Code reusability.
View state diagram
Attachment
/Dettachme
nt

Traversals

State
save/restor
e
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()
Traversals
onMe
asure()

onLa
yout()

Animate

onDr
aw()

invalidate()
requestLayout()
● Animation events will always happen
before measure
● A required measure will always happen
before layout
● A required layout will always happen
before draw
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];
}

}
};
}
}
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().
Traversals are expensive
FrameLayout

LinearLayout

TextView

ImageView

TextView

When a view calls requestLayout()
or invalidate() its parent and all its
parents’ parents call it, until the root
parent.
Traversals are expensive
FrameLayout

LinearLayout

TextView

ImageView

TextView

onMeasure(), onLayout() and
onDraw() are called for all the
children of its view.
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.
Coffee time!

Thank you for your patience...
Sources
1.
2.
3.
4.
5.

Writing custom views for android google io 2013 http://commondatastorage.googleapis.com/io-2013/presentations/109%
20-%20Custom%20Views%20in%20Android.pdf
http://developer.android.com/reference/android/view/View.html
Crafting Custom Android Views (en) - DroidCon Paris 2013 http://www.youtube.com/watch?v=YIArVywQe8k
http://stackoverflow.com/questions/3542333/how-to-prevent-custom-views-from-losing-state-across-screen-orientationchanges/3542895#3542895
http://rajeshvijayakumar.blogspot.co.uk/2013/01/custom-view-example-in-android.html

Weitere ähnliche Inhalte

Was ist angesagt?

Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Korhan Bircan
 
Deep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerViewDeep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerViewTakeshi Hagikura
 
Android 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkAndroid 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkJussi Pohjolainen
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded GraphicsAdil Jafri
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsNaman Dwivedi
 
Square selection function
Square selection functionSquare selection function
Square selection functionGeorge Scott IV
 

Was ist angesagt? (9)

Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)
 
Deep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerViewDeep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerView
 
Android 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkAndroid 2D Drawing and Animation Framework
Android 2D Drawing and Animation Framework
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded Graphics
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animations
 
Maya
MayaMaya
Maya
 
Mxd Snapping
Mxd Snapping Mxd Snapping
Mxd Snapping
 
MIDP: Game API
MIDP: Game APIMIDP: Game API
MIDP: Game API
 
Square selection function
Square selection functionSquare selection function
Square selection function
 

Ähnlich wie Android custom views

Making it fit - DroidCon Paris 18 june 2013
Making it fit - DroidCon Paris 18 june 2013Making it fit - DroidCon Paris 18 june 2013
Making it fit - DroidCon Paris 18 june 2013Paris Android User Group
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Managing Complex UI using xState
Managing Complex UI using xStateManaging Complex UI using xState
Managing Complex UI using xStateXavier Lozinguez
 
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, ClimacellLiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, ClimacellDroidConTLV
 
MVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) DetailsMVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) DetailsFlorina Muntenescu
 
Dn d clipboard
Dn d clipboardDn d clipboard
Dn d clipboardpinnamur
 
Dn d clipboard
Dn d clipboardDn d clipboard
Dn d clipboardpinnamur
 
Dn d clipboard
Dn d clipboardDn d clipboard
Dn d clipboardpinnamur
 
Survive the lifecycle
Survive the lifecycleSurvive the lifecycle
Survive the lifecycleSimon Joecks
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr TolstykhCodeFest
 
Mastering RecyclerView Layouts
Mastering RecyclerView LayoutsMastering RecyclerView Layouts
Mastering RecyclerView LayoutsDave Smith
 
Android Jetpack: ViewModel and Testing
Android Jetpack: ViewModel and TestingAndroid Jetpack: ViewModel and Testing
Android Jetpack: ViewModel and TestingYongjun Kim
 
Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...DroidConTLV
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsDiego Grancini
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesMarakana Inc.
 
Android UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesAndroid UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesEdgar Gonzalez
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3Jieyi Wu
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 

Ähnlich wie Android custom views (20)

Making it fit - DroidCon Paris 18 june 2013
Making it fit - DroidCon Paris 18 june 2013Making it fit - DroidCon Paris 18 june 2013
Making it fit - DroidCon Paris 18 june 2013
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Managing Complex UI using xState
Managing Complex UI using xStateManaging Complex UI using xState
Managing Complex UI using xState
 
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, ClimacellLiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
 
MVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) DetailsMVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) Details
 
Dn d clipboard
Dn d clipboardDn d clipboard
Dn d clipboard
 
Dn d clipboard
Dn d clipboardDn d clipboard
Dn d clipboard
 
Dn d clipboard
Dn d clipboardDn d clipboard
Dn d clipboard
 
Survive the lifecycle
Survive the lifecycleSurvive the lifecycle
Survive the lifecycle
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
 
Mastering RecyclerView Layouts
Mastering RecyclerView LayoutsMastering RecyclerView Layouts
Mastering RecyclerView Layouts
 
Flutter
FlutterFlutter
Flutter
 
Android Jetpack: ViewModel and Testing
Android Jetpack: ViewModel and TestingAndroid Jetpack: ViewModel and Testing
Android Jetpack: ViewModel and Testing
 
Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and Techniques
 
Android UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesAndroid UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and Techniques
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 

Kürzlich hochgeladen

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Kürzlich hochgeladen (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Android custom views

  • 2. Why custom views 1. Unique UX. 2. Optimised performance. 3. Code reusability.
  • 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()
  • 5. Traversals onMe asure() onLa yout() Animate onDr aw() invalidate() requestLayout() ● Animation events will always happen before measure ● A required measure will always happen before layout ● A required layout will always happen before draw
  • 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().
  • 8. Traversals are expensive FrameLayout LinearLayout TextView ImageView TextView When a view calls requestLayout() or invalidate() its parent and all its parents’ parents call it, until the root parent.
  • 9. Traversals are expensive FrameLayout LinearLayout TextView ImageView TextView onMeasure(), onLayout() and onDraw() are called for all the children of its view.
  • 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.
  • 11. Coffee time! Thank you for your patience...
  • 12. Sources 1. 2. 3. 4. 5. Writing custom views for android google io 2013 http://commondatastorage.googleapis.com/io-2013/presentations/109% 20-%20Custom%20Views%20in%20Android.pdf http://developer.android.com/reference/android/view/View.html Crafting Custom Android Views (en) - DroidCon Paris 2013 http://www.youtube.com/watch?v=YIArVywQe8k http://stackoverflow.com/questions/3542333/how-to-prevent-custom-views-from-losing-state-across-screen-orientationchanges/3542895#3542895 http://rajeshvijayakumar.blogspot.co.uk/2013/01/custom-view-example-in-android.html