SlideShare a Scribd company logo
Custom views
Matej Vukosav
05.04.2018
Agenda
- Just custom views
Android Custom views
Coding options
1. bunch of default android views
- easier to code
- faster
2. custom views
Should we use custom views?
Why DO?
- code readability
Why DO?
- code readability
- reusability
Why DO?
- code readability
- reusability
- improved performance
Why DO?
- code readability
- reusability
- improved performance
- endless possibilities
Why NOT?
- Can be tricky to implement
Why NOT?
- Can be tricky to implement
- Time consuming
- you need to handle everything by yourself
- style, font, text size, rendering on different screens, scaling, aspect ratio, zoom,
- all kind of click listeners, orientation
Why NOT?
- Can be tricky to implement
- Time consuming
- you need to handle everything by yourself
- style, font, text size, rendering on different screens, scaling, aspect ratio, zoom,
- all kind of click listeners, orientation
- required more coding skill
Ideas
?
Ideas
- volume control
Ideas
- volume control
- color picker
Ideas
- volume control
- color picker
- compass
Ideas
- volume control
- color picker
- compass
- graph
Ideas
- volume control
- color picker
- compass
- graphs
Ideas
- volume control
- color picker
- compass
- graph
- measurement
Ideas
- volume control
- color picker
- compass
- graph
- measurement
Ideas
- volume control
- color picker
- compass
- graph
- measurement
Ideas
- volume control
- color picker
- compass
- graph
- measurement
Ideas
- volume control
- color picker
- compass
- graph
- measurement
Android Custom views
How Android draw
views?
How Android draws views?
XML layout -> instantiated -> inflated -> allocated views ->
How Android draws views?
XML layout -> instantiated -> inflated -> allocated views -> view hierarchy
How Android draws views?
Phases before view hierarchy comes to screen:
1. measure
2. layout
3. draw
How Android draws views?
Phases before view hierarchy comes to screen:
1. measure -> onMeasure()
2. layout
3. draw
How Android draws views?
Phases before view hierarchy comes to screen:
1. measure -> onMeasure()
2. layout -> onLayout()
3. draw
How Android draws views?
Phases before view hierarchy comes to screen:
1. measure -> onMeasure()
2. layout -> onLayout()
3. draw -> onDraw()
How Android draws views?
Phases before view hierarchy comes to screen:
1. measure -> onMeasure()
a. measure the view and its content
b. find how big view should be
c. must call setMeasuredDimension( width, height)
2. layout -> onLayout()
3. draw -> onDraw()
How Android draws views?
Phases before view hierarchy comes to screen:
1. measure -> onMeasure()
2. layout -> onLayout()
a. assign a size and position to each of its children
3. draw -> onDraw()
How Android draws views?
Phases before view hierarchy comes to screen:
1. measure -> onMeasure()
2. layout -> onLayout()
3. draw -> onDraw()
a. draw on canvas
How do we
draw?
Approaches
2 general ways
Approaches
2 general ways
- extend the existing view class
- Button, TextView, EditText, CheckBox, RadioButton
Approaches
2 general ways
- extend the existing view class
- Button, TextView, EditText, CheckBox, RadioButton
- extend the base view class/group class
Approaches
2 general ways
- extend the existing view class
- Button, TextView, EditText, CheckBox, RadioButton
- extend the base view class/group class
Extend the view base class
- extend View class (or subclass)
import android.view.View;
public class MyCustomView extends View{
...
}
Extend the view base class
- extend View class (or subclass)
- constructors
import android.view.View;
public class MyCustomView extends View{
...
}
Extend the view base class
- extend View class (or subclass)
- constructors
- 4 of them
import android.view.View;
public class MyCustomView extends View{
}
Extend the view base class
- extend View class (or subclass)
- constructors
- 4 of them
- but we only need 2
import android.view.View;
public class MyCustomView extends View{
}
Constructors
1. Create new from code - View (Context context)
2. Create from XML - View(Context context, AttributeSet attrs)
3. Create from XML with a style from theme attribute - View(Context
context,AttributeSet atts, int deffStyleAttr)
4. Create from XML with a style from theme attribute or style resource -
View(Context context,AttributeSet atts, int deffStyleAttr, int defStyleRes)
Constructors
1. Create new from code - View (Context context)
2. Create from XML - View(Context context, AttributeSet attrs)
3. Create from XML with a style from theme attribute - View(Context
context,AttributeSet atts, int deffStyleAttr)
4. Create from XML with a style from theme attribute or style resource -
View(Context context,AttributeSet atts, int deffStyleAttr, int defStyleRes)
Constructors
1. Create new from code - View (Context context)
2. Create from XML - View(Context context, AttributeSet attrs)
3. Create from XML with a style from theme attribute - View(Context
context,AttributeSet atts, int deffStyleAttr)
4. Create from XML with a style from theme attribute or style resource -
View(Context context,AttributeSet atts, int deffStyleAttr, int defStyleRes)
Constructors
1. Create new from code - View (Context context)
2. Create from XML - View(Context context, AttributeSet attrs)
3. Create from XML with a style from theme attribute - View(Context
context,AttributeSet atts, int deffStyleAttr)
4. Create from XML with a style from theme attribute or style resource -
View(Context context,AttributeSet atts, int deffStyleAttr, int defStyleRes)
Constructors
1. Create new from code - View (Context context)
2. Create from XML - View(Context context, AttributeSet attrs)
3. Create from XML with a style from theme attribute - View(Context
context,AttributeSet atts, int deffStyleAttr)
4. Create from XML with a style from theme attribute or style resource -
View(Context context,AttributeSet atts, int deffStyleAttr, int defStyleRes)
Constructors
Don’t chain constructors using this!
Constructors
Don’t chain constructors using this!
public CustomTextView( Context context ) {
this( context, null );
}
public CustomTextView( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
public CustomTextView( Context context, AttributeSet attrs, int defStyleAttr )
{
super( context, attrs, defStyleAttr );
...more code...
}
Constructors
Don’t chain constructors using this!
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
android:text="This is some random irrelevant text."/>
<com.vuki.custom.view.CustomTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text_view"
...
android:text="This is some random irrelevant text."/>
Constructors
Don’t chain constructors using this!
Constructors
Don’t chain constructors using this!
public CustomTextView( Context context ) {
this( context, null );
}
public CustomTextView( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
public CustomTextView( Context context, AttributeSet attrs, int defStyleAttr )
{
super( context, attrs, defStyleAttr );
...more code...
}
Constructors
Don’t chain constructors using this!
public CustomTextView( Context context ) {
this( context, null );
}
public CustomTextView( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
public CustomTextView( Context context, AttributeSet attrs, int defStyleAttr )
{
super( context, attrs, defStyleAttr );
...more code...
}
Constructors
Don’t chain constructors using this!
public CustomTextView( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
Constructors
Don’t chain constructors using this!
public CustomTextView( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
TEXT VIEW CLASS
public TextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.textViewStyle);
}
super(context, attrs, defStyleAttr );
Constructors
Don’t chain constructors using this!
public CustomTextView( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
public TextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.textViewStyle);
}
super(context, attrs, defStyleAttr ); ??
Constructors
public CustomTextView( Context context ) {
super( context );
init();
}
public CustomTextView( Context context, AttributeSet attrs ) {
super( context, attrs);
init();
}
public CustomTextView( Context context, AttributeSet attrs, int defStyleAttr )
{
super( context, attrs, defStyleAttr );
init();
}
void init(){
...more code..
}
Ok! Can we finally draw
something?
Steps
- extend View class (or subclass)
- constructors - DONE ✔️
- override methods
Steps
- extend View class (or subclass)
- constructors - DONE ✔️
- override methods ( starts with ‘on’ )
- onDraw()
- onMeasure()
- onLayout()
- onSizeChanged()
- ...
Steps
- extend View class (or subclass)
- constructors - DONE ✔️
- override methods ( starts with ‘on’ )
- onDraw()
- onMeasure()
- onLayout()
- onSizeChanged()
onDraw()
- delivers canvas
- draw
- 2D graphics,
- other standard or custom components,
- styled text,
- or anything else you can think of.
Primitives
- lines -> drawLine(..)
- circles -> drawCircle(...)
- rectangles -> drawRect(..)
- oval -> drawOval(...)
- points -> drawPoint(..)
Car?
Ugly Car?
Ugly Car?
Ugly Car?
canvas.drawCircle(x1,y1,radius,paint) canvas.drawCircle(x2,y2,radius,paint)
canvas.drawRect(rect1, paint)
canvas.drawRect(rect1, paint)
What we can do to make it
better?
What we can do to make it better?
Introduce:
- Paint
Paint
- “class that holds the style and color information about how to draw
geometries, text and bitmap”
- canvas.drawSomething( params… , paint)
What we can do to make it better?
Introduce:
- Paint
- Path
Path
- moveTo()
- lineTo()
- bezier
- quadTo() - quadratic bezier
- cubicTo() - cubic bezier
- clipping path
- op (Path, Op)
Path
- moveTo()
- lineTo()
- bezier
- quadTo() - quadratic bezier
- cubicTo() - cubic bezier
- clipping path
- op (Path, Op)
Path
- moveTo()
- lineTo()
- bezier
- quadTo() - quadratic bezier
- cubicTo() - cubic bezier
- clipping path
- op (Path, Op)
- The logical operation that can be performed
when combining two paths.
Ugly Car?
Car
Car
drawPath(path, paint)
What we can do to make it better?
Introduce:
- Paint
- Path
- Shaders
Shaders
“Shader is the based class for objects that return horizontal spans of colors during
drawing.”
Shaders
- LinearGradient
- RadialGradient
- SweepGradient
- BitmapGradient
- ComposeGradient
Shaders
- LinearGradient
- RadialGradient
- SweepGradient
- BitmapGradient
- ComposeGradient
Shaders
- LinearGradient
- RadialGradient
- SweepGradient
- BitmapGradient
- ComposeGradient
Shaders
- LinearGradient
- RadialGradient
- SweepGradient
- BitmapGradient
- ComposeGradient
Shaders
- LinearGradient
- RadialGradient
- SweepGradient
- BitmapGradient
- ComposeGradient
Shaders
- LinearGradient
- RadialGradient
- SweepGradient
- BitmapGradient
- ComposeGradient
ColorFilter
- used with Paint
- modify color of pixels
- LightningColorFilter
- ColorMatrixColorFilter
- PorterDuffColorFilter
ColorFilter
- LightningColorFilter
- ColorMatrixColorFilter
- PorterDuffColorFilter
ColorFilter
- LightningColorFilter
- ColorMatrixColorFilter
- PorterDuffColorFilter
InvertColorMatrix
1, 0, 0, 0, 0 // red
0, 1, 0, 0, 0 //green
0, 0, 1, 0, 0 //blue
0, 0, 0, 1, 0 //alpha
new ColorMatrixColorFilter (matrix)
Grayscale
Sepia
ColorFilter
- LightningColorFilter
- ColorMatrixColorFilter
- PorterDuffColorFilter
PorterDuff.Mode
- “Composing Digital Images”
- 12 compositing operators
- alpha compositing modes
PorterDuff.Mode
- 12 compositing operators
- alpha compositing modes
- blending modes
ColorFilter
- LightningColorFilter
- ColorMatrixColorFilter
- PorterDuffColorFilter
PorterDuff.Mode.SRC_IN
PorterDuff.Mode.XOR
What
else?
Exhaust?
Exhaust?
Electric is better
Animations
- animating view properties
Animations
- ObjectAnimator
- animate with reflection
- ViewPropertyAnimator
- animate some of standard view
properties
- ValueAnimator
- animate some of standar
- AnimatorSet
- chain multiple animators
ObjectAnimator animX =
ObjectAnimator.ofFloat(myView, "x", 50f);
- view must have setter for property
- automatically update the view
Animations
- ObjectAnimator
- animate with reflection
- ViewPropertyAnimator
- animate some of standard view
properties
- ValueAnimator
- animate some of standar
- AnimatorSet
- chain multiple animators
someView.animate()
.alpha(1f)
.scaleX(2.f)
.scaleY(1.f);
Animations
- ObjectAnimator
- animate with reflection
- ViewPropertyAnimator
- animate some of standard view
properties
- ValueAnimator
- any number of properties
- AnimatorSet
- chain multiple animators
PropertyValuesHolder
- holds information about a property
valueAnimator
.setInterpolator( new LinearInterpolator() )
.setEvaluator( new FloatEvaluator() )
.setDuration( 3000 )
.setRepeatCount( INFINITE )
.setRepeatMode( RESTART)
- must implement update listener
Animations
- ObjectAnimator
- animate with reflection
- ViewPropertyAnimator
- animate some of standard view
properties
- ValueAnimator
- any number of properties
- AnimatorSet
- chain multiple animators
PropertyValuesHolder x;
PropertyValuesHolder y;
x=PropertyValuesHolder.ofFloat(“propX”,0,5f)
y=PropertyValuesHolder.ofInt(“propY”,0,30)
valueAnimator.setValues(x,y);
valueAnimator.addUpdateListener({
…..
=animation.getAnimatedValue(“propX”)
=animation.getAnimatedValue(“propY”)
….
})
Animations
- ObjectAnimator
- animate with reflection
- ViewPropertyAnimator
- animate some of standard view
properties
- ValueAnimator
- any number of properties
- PropertyValueHolder
- AnimatorSet
- chain multiple animators
animatorSet
.playSequentially( anim1, anim2)
.playTogether( anim1, anim2 )
State changed
- requestLayout()
- view update through its lifecycle
- invalidate()
- redraw the view
- invalidate from UI thread
- postInvalidate()
- invalidate from non UI thread
Animations
valueAnimator.addUpdateListener({
…..
=animation.getAnimatedValue(“propX”)
=animation.getAnimatedValue(“propY”)
invalidate()
….
})
Animations
Animations
The Car
Now you know
- View anatomy
- How Android draw views
- How we draw views
- View constructors
- View methods
- Paint
- Path
- Shaders
- ColorFilter
- Animations
Takeaway
- don’t instantiate objects in onDraw() method!!
- clipping is expensive!
- eliminate unnecessary calls to invalidate()
- chain animation properties
- endless possibilities
- it’s fun!
What you can’t do
- create 3D graphics (need to use SurfaceView)
Conclusion
Literature
http://chiuki.github.io/android-shaders-filters/#/
https://engineering.upgrad.com/custom-views-in-android-80da90f7d683
https://medium.com/@britt.barak/layout-once-layout-twice-sold-aef156ff16a4
https://medium.com/@britt.barak/measure-layout-draw-483c6a4d2fab
https://robots.thoughtbot.com/android-interpolators-a-visual-guide
https://android.jlelse.eu/become-an-android-painter-aadf91cec9d4
Literature
https://android-developers.googleblog.com/2011/05/introducing-
viewpropertyanimator.htm
http://blog.danlew.net/2016/07/19/a-deep-dive-into-android-view-constructors/
https://developer.android.com/guide/topics/ui/custom-components.html
https://academy.realm.io/posts/360andev-huyen-tue-dao-measure-layout-
draw-repeat-custom-views-and-viewgroups-android/
https://medium.com/google-developers/draw-what-you-see-and-clip-the-e11-
out-of-the-rest-6df58c47873e
Literature
https://developer.android.com/training/custom-views/create-view.html
https://code.tutsplus.com/tutorials/manipulate-visual-effects-with-the-
colormatrixfilter-and-convolutionfilter--active-3221#comment-45378
https://tech.recruit-mp.co.jp/mobile/remember_canvas2/
https://www.w3.org/TR/SVG/painting.html#FillProperties
https://developer.android.com/guide/topics/resources/animation-resource.html
https://developer.android.com/guide/topics/graphics/prop-
animation.html#object-animator
Images
1. https://2.bp.blogspot.com/-
yFADYUlhdy8/WDPAvFCV0NI/AAAAAAAAnmk/b5-
p6q39_N0bt5eThqtv65yZz4MIg3l8gCLcB/s1600/Crossroads-choice-
dilemma-580x427.jpg
2. http://www.cartoonspot.net/looney-tunes/road-runner-picture.php
Code examples
https://github.com/MatejVukosav/ConceptVie
w
Thank
you

More Related Content

Similar to Android Custom views (20)

PPTX
Making it fit - DroidCon Paris 18 june 2013
Paris Android User Group
 
ODP
Android App Development - 04 Views and layouts
Diego Grancini
 
PDF
Custom UI Components at Android Only 2011
Johan Nilsson
 
PDF
Android development for iOS developers
Darryl Bayliss
 
PDF
Custom components
nazmulhossain32
 
ODP
2013.05.02 android-l1
heath0504
 
PPT
Lec005 android start_program
Eyad Almasri
 
PDF
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
PPT
Hello Android
Trong Dinh
 
PPS
Actionview
Amal Subhash
 
KEY
Sass Essentials at Mobile Camp LA
Jake Johnson
 
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
PPTX
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
Sencha
 
PDF
Android Screen Containers & Layouts
Vijay Rastogi
 
PDF
How to Become the MacGyver of Android Custom Views
Fernando Cejas
 
PDF
07_UIAndroid.pdf
ImranS18
 
PPT
View groups containers
Mani Selvaraj
 
PDF
Responsive mobile design in practice
Kirill Grouchnikov
 
PPTX
Android Custom Views
Babar Sanah
 
PDF
Accessibility Testing using Axe
RapidValue
 
Making it fit - DroidCon Paris 18 june 2013
Paris Android User Group
 
Android App Development - 04 Views and layouts
Diego Grancini
 
Custom UI Components at Android Only 2011
Johan Nilsson
 
Android development for iOS developers
Darryl Bayliss
 
Custom components
nazmulhossain32
 
2013.05.02 android-l1
heath0504
 
Lec005 android start_program
Eyad Almasri
 
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
Hello Android
Trong Dinh
 
Actionview
Amal Subhash
 
Sass Essentials at Mobile Camp LA
Jake Johnson
 
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
Sencha
 
Android Screen Containers & Layouts
Vijay Rastogi
 
How to Become the MacGyver of Android Custom Views
Fernando Cejas
 
07_UIAndroid.pdf
ImranS18
 
View groups containers
Mani Selvaraj
 
Responsive mobile design in practice
Kirill Grouchnikov
 
Android Custom Views
Babar Sanah
 
Accessibility Testing using Axe
RapidValue
 

Recently uploaded (20)

PPTX
Introduction to web development | MERN Stack
JosephLiyon
 
PDF
Laboratory Workflows Digitalized and live in 90 days with Scifeon´s SAPPA P...
info969686
 
PDF
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
PDF
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
PPTX
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PDF
Power BI vs Tableau vs Looker - Which BI Tool is Right for You?
MagnusMinds IT Solution LLP
 
PDF
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
PPTX
How Can Recruitment Management Software Improve Hiring Efficiency?
HireME
 
PDF
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
 
PDF
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
PPTX
computer forensics encase emager app exp6 1.pptx
ssuser343e92
 
PPTX
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
PPTX
For my supp to finally picking supp that work
necas19388
 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
Introduction to web development | MERN Stack
JosephLiyon
 
Laboratory Workflows Digitalized and live in 90 days with Scifeon´s SAPPA P...
info969686
 
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
Power BI vs Tableau vs Looker - Which BI Tool is Right for You?
MagnusMinds IT Solution LLP
 
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
How Can Recruitment Management Software Improve Hiring Efficiency?
HireME
 
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
 
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
Rewards and Recognition (2).pdf
ethan Talor
 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
computer forensics encase emager app exp6 1.pptx
ssuser343e92
 
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
For my supp to finally picking supp that work
necas19388
 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
Ad

Android Custom views