SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
"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
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 

Dernier (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
"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 ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

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