SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
Android UI Development:
Tips, Tricks, and Techniques
                      Romain Guy
                       Chet Haase
           Android UI Toolkit Team
                           Google
Android UI Development:
          rrific Tips,Tricks, and Techniques
    lly Te
Tota
                                      Romain Guy
                                       Chet Haase
                           Android UI Toolkit Team
                                           Google
Trash Talk
Trash Talk
            or
Garbage Zero
  Avoid creating garbage,
when necessary and possible
Statics as Temporaries
• Instead of a temporary object:
    public boolean pointInArea(int x, int y, Area area) {
      Point testPoint = new Point(x, y);
      return area.intersect(testPoint);
    }


• Consider a static instead:
    static final Point tmpPoint = new Point();

    public boolean pointInArea(int x, int y, Area area) {
      tmpPoint.x = x;
      tmpPoint.y = y;
      return area.intersect(tmpPoint.yPoint);
    }


                                                       5
AutoBoxing
• Autoboxing creates Objects

     float x = 5;
     Float y = x;
     doSomething(x);

     void doSomething(Float z) {}



                       is equivalent to
     float x = 5;
     Float y = new Float(x);
     doSomething(new Float(x));

     void doSomething(Float z) {}


                                          6
De-Autoboxing
• Use primitive types whenever possible
 –Avoids Object creation
• Use types you need for the situation
 –Avoids autoboxing back and forth




                                          7
Obliterator
• The enhanced for() loop is great
• ... but creates garbage
          for (Node node : nodeList) {}


               is equivalent to
          Iterator iter = nodeList.iterator();
          while (iter.hasNext()) {}


• Consider a size check first:
          if (nodeList.size() > 0) {
            for (Node node : nodeList) {}
          }


                                                 8
Image is Everything
• Recycle those Bitmaps
  –Device resources are limited
• Finalizers will clear them ... eventually
• You might think this would help
         // done using this one, clear reference
         myBitmap = null;

• But you really want to do this
         // done using this one, recycle it
         myBitmap.recycle();

• Don’t wait for the finalizer to do the work if you
  need that memory now

                                                   9
Varargh
• Parameters to varargs method packaged into a
  temporary array
       void someMethod(float... args) {}

       someMethod(5f);


               is equivalent to
       someMethod(new float[]{5});




                                           10
Gener-ick
• T doesn’t stand for “primitive Type”
             public class MyClass<T> {
               T myVar;
               MyClass<T>(T arg) {
                 myVar = arg;
               }
             }

• Generics only deal with Objects; primitive types
  get autoboxed
            float f;
            MyClass<Float> myObject =
              new MyClass<Float>(f);

            which is equivalent to
            MyClass<Float> myObject =
              new MyClass<Float>(new Float(f));
                                                  11
Tools: Allocation Tracking
• Limit allocations to find problems
        int prevLimt = -1;
        try {
          prevLimit =
        Debug.setAllocationLimit(0);
          // Do stuff
        } finally {
          Debug.setAllocationLimit(-1);
        }

• Count the allocations being made
        Debug.startAllocationCounting();
        // do stuff
        int allocCount = Debug.getThreadAllocCount();
        Debug.stopAllocationCounting);



                                                        12
Tools: DDMS
• Visual tool helps track allocations down to the
  object/file/line number
• (demo)




                                           13
Watch the Garbage...
But Don’t Be Silly
• As Michael Abrash might have said:
                                 ViewRoot
 –“Premature optimization is the Root of all evil”


• Minor garbage is irrelevant in most cases
• But if you have GCs at critical points in your
  application, consider Garbage Zero
 –Example: animations

                                                 14
Tools: hat
• DDMS
• Heap Analysis Tool is used to track down
  memory leaks
• adb shell dumpsys meminfo <process>




                                         15
Memory leaks
• Be careful with Context
• Be careful with static fields
• Avoid non-static inner classes
• Use weak references




                                   16
YOU and I
Responsiveness
• Single-threaded UI
• Don’t block the UI thread
 – Also called main thread
• AsyncTask
 – Worker thread and UI thread messaging
• Handler
 – Messaging




                                           18
Overinvalidating
• Only redraw what you must
• (demo)




                              19
Fewer is better
• Many views
 – Slower layout
 – Slower drawing
 – Slower startup time
• Deep hierarchies
 – Memory
 – Slow...
 – StackOverflowException



                            20
HiearchyViewer
Layout optimizations
• Custom views
• Custom layouts
• <merge />
• ViewStub
• Compound drawables
• layoutopt




                       22
ViewStub




           23
ViewStub




           24
ViewStub

   <ViewStub
       android:id="@+id/stub_import"
       android:inflatedId="@+id/panel_import"

       android:layout="@layout/progress_overlay"

       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_gravity="bottom" />




                                                25
ViewStub



findViewById(R.id.stub_import).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub)
        findViewById(R.id.stub_import)).inflate();




                                                  26
<merge/>




           27
<merge/>



<!-- The merge tag must be the root tag -->
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Content -->
</merge>




                                                        28
Compound drawables
   <LinearLayout
       android:orientation="horizontal"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content">

       <ImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/icon" />
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@string/hello" />

   </LinearLayout>

                                               29
Compound drawables


   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/hello"
       android:drawableLeft="@drawable/icon" />




                                                  30
layoutopt
ListView


  1 public View getView(int position, View convertView, ViewGroup parent) {
  2     View item = mInflater.inflate(R.layout.list_item_icon_text, null);

  3     ((TextView) item.findViewById(R.id.text)).setText(DATA[position]);
  4     ((ImageView) item.findViewById(R.id.icon)).setImageBitmap(
  5             (position & 1) == 1 ? mIcon1 : mIcon2);

  6     return item;
  7 }




                                                                32
ListView


1 public View getView(int position, View convertView, ViewGroup parent) {
2     if (convertView == null) {
3         convertView = mInflater.inflate(R.layout.item, parent, false);
4     }

5     ((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]);
6     ((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap(
7             (position & 1) == 1 ? mIcon1 : mIcon2);

8     return convertView;
9 }




                                                                 33
ListView


           static class ViewHolder {
               TextView text;
               ImageView icon;
           }




                                       34
ListView
  1 public View getView(int position, View convertView, ViewGroup parent) {
  2     ViewHolder holder;
  3
  4     if (convertView == null) {
  5         convertView = mInflater.inflate(R.layout.list_item_icon_text,
  6                 parent, false);
  7         holder = new ViewHolder();
  8         holder.text = (TextView) convertView.findViewById(R.id.text);
  9         holder.icon = (ImageView) convertView.findViewById(R.id.icon);
 10
 11         convertView.setTag(holder);
 12     } else {
 13         holder = (ViewHolder) convertView.getTag();
 14     }
 15
 16     holder.text.setText(DATA[position]);
 17     holder.icon.setImageBitmap((position & 1) ==? mIcon1 : mIcon2);
 18
 19     return convertView;
 20 }

                                                                35
ListView
   60.0

   50.0

   40.0

   30.0

   20.0

   10.0

     0
            Dumb             Correct            Fast
           List of 10,000 items on NexusOne, Android 2.2
                                                       36
Graphics optimizations
• Pre-scale bitmaps
• Use compatible bitmaps
 – ARGB_8888 to draw on 32 bits window
• Avoid blending
• Use View drawing caches
 – View.setDrawingCacheEnabled(true)
• View.isOpaque()



                                         37
For More Information
• Android developer site
 –developer.android.com
• Romain
 –@romainguy
 –curious-creature.org
• Chet
 –@chethaase
 –graphics-geek.blogspot.com



                               38

Contenu connexe

Tendances

[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」techtalkdwango
 
openFrameworks 007 - utils
openFrameworks 007 - utilsopenFrameworks 007 - utils
openFrameworks 007 - utilsroxlu
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정SeungChul Kang
 
오브젝트C(pdf)
오브젝트C(pdf)오브젝트C(pdf)
오브젝트C(pdf)sunwooindia
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Alexander Granin
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptMichael Girouard
 
Real world cats
Real world catsReal world cats
Real world catsIkhoon Eom
 
openFrameworks 007 - GL
openFrameworks 007 - GL openFrameworks 007 - GL
openFrameworks 007 - GL roxlu
 
Functional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsFunctional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsAlexander Granin
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersJoris Verbogt
 

Tendances (19)

[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」
 
openFrameworks 007 - utils
openFrameworks 007 - utilsopenFrameworks 007 - utils
openFrameworks 007 - utils
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정
 
오브젝트C(pdf)
오브젝트C(pdf)오브젝트C(pdf)
오브젝트C(pdf)
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Real world cats
Real world catsReal world cats
Real world cats
 
openFrameworks 007 - GL
openFrameworks 007 - GL openFrameworks 007 - GL
openFrameworks 007 - GL
 
Functional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsFunctional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonads
 
Responsible JavaScript
Responsible JavaScriptResponsible JavaScript
Responsible JavaScript
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
 

En vedette

Camera shots
Camera shotsCamera shots
Camera shotsecsmedia
 
Pure fast001
Pure fast001Pure fast001
Pure fast001dflexer
 
Materials and properties
Materials and propertiesMaterials and properties
Materials and propertiesAlison Hardy
 
Making The Transition
Making The TransitionMaking The Transition
Making The TransitionAndre Pope
 
А что будет с командой? (Yandex & SPB Software)
А что будет с командой? (Yandex & SPB Software)А что будет с командой? (Yandex & SPB Software)
А что будет с командой? (Yandex & SPB Software)Ксения Артеменко
 
Science item collection
Science item collectionScience item collection
Science item collectionXiomara Jones
 
Finn-ID RFID-kiertueella 2010: case Honkarakenne
Finn-ID RFID-kiertueella 2010: case HonkarakenneFinn-ID RFID-kiertueella 2010: case Honkarakenne
Finn-ID RFID-kiertueella 2010: case HonkarakenneFinn-ID Oy
 
Angle shots
Angle shotsAngle shots
Angle shotsecsmedia
 
Location shots
Location shotsLocation shots
Location shotsbeealex
 
Making Smart Choices: Data-Driven Decision Making in Academic Libraries
Making Smart Choices: Data-Driven Decision Making in Academic LibrariesMaking Smart Choices: Data-Driven Decision Making in Academic Libraries
Making Smart Choices: Data-Driven Decision Making in Academic LibrariesMichael Levine-Clark
 
罗兰贝格战略采购报告(Ppt 112)
罗兰贝格战略采购报告(Ppt 112)罗兰贝格战略采购报告(Ppt 112)
罗兰贝格战略采购报告(Ppt 112)datoufa
 
Funda gürbüz(twitter)
Funda gürbüz(twitter)Funda gürbüz(twitter)
Funda gürbüz(twitter)funda91
 
Mongols ballad
Mongols balladMongols ballad
Mongols balladbobbymoore
 
Standard procedure for selecting hospitality industry employees
Standard procedure for selecting hospitality industry employeesStandard procedure for selecting hospitality industry employees
Standard procedure for selecting hospitality industry employeesluisocampo88
 

En vedette (20)

Camera shots
Camera shotsCamera shots
Camera shots
 
Pure fast001
Pure fast001Pure fast001
Pure fast001
 
Use power point
Use power pointUse power point
Use power point
 
Mark Davis
Mark Davis Mark Davis
Mark Davis
 
Sida
SidaSida
Sida
 
Materials and properties
Materials and propertiesMaterials and properties
Materials and properties
 
Making The Transition
Making The TransitionMaking The Transition
Making The Transition
 
SMCMUC Social CRM
SMCMUC Social CRMSMCMUC Social CRM
SMCMUC Social CRM
 
А что будет с командой? (Yandex & SPB Software)
А что будет с командой? (Yandex & SPB Software)А что будет с командой? (Yandex & SPB Software)
А что будет с командой? (Yandex & SPB Software)
 
Science item collection
Science item collectionScience item collection
Science item collection
 
Finn-ID RFID-kiertueella 2010: case Honkarakenne
Finn-ID RFID-kiertueella 2010: case HonkarakenneFinn-ID RFID-kiertueella 2010: case Honkarakenne
Finn-ID RFID-kiertueella 2010: case Honkarakenne
 
Angle shots
Angle shotsAngle shots
Angle shots
 
Sn i sentits EAT (2016)
Sn i sentits EAT (2016)Sn i sentits EAT (2016)
Sn i sentits EAT (2016)
 
Location shots
Location shotsLocation shots
Location shots
 
Oltre l'orientamento
Oltre l'orientamentoOltre l'orientamento
Oltre l'orientamento
 
Making Smart Choices: Data-Driven Decision Making in Academic Libraries
Making Smart Choices: Data-Driven Decision Making in Academic LibrariesMaking Smart Choices: Data-Driven Decision Making in Academic Libraries
Making Smart Choices: Data-Driven Decision Making in Academic Libraries
 
罗兰贝格战略采购报告(Ppt 112)
罗兰贝格战略采购报告(Ppt 112)罗兰贝格战略采购报告(Ppt 112)
罗兰贝格战略采购报告(Ppt 112)
 
Funda gürbüz(twitter)
Funda gürbüz(twitter)Funda gürbüz(twitter)
Funda gürbüz(twitter)
 
Mongols ballad
Mongols balladMongols ballad
Mongols ballad
 
Standard procedure for selecting hospitality industry employees
Standard procedure for selecting hospitality industry employeesStandard procedure for selecting hospitality industry employees
Standard procedure for selecting hospitality industry employees
 

Similaire à Android UI Development: Tips, Tricks, and Techniques

ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013Mathias Seguy
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom componentsJeremy Grancher
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientBin Shao
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
Creating custom views
Creating custom viewsCreating custom views
Creating custom viewsMu Chun Wang
 
Android Support Library
Android Support LibraryAndroid Support Library
Android Support LibraryAlexey Ustenko
 
Jollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-levelJollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-levelJollen Chen
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowRomain Dorgueil
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35Bilal Ahmed
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recieversUtkarsh Mankad
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsNaman Dwivedi
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろうUnity Technologies Japan K.K.
 
Introduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R ShinyIntroduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R Shinyanamarisaguedes
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Kevin Juma
 

Similaire à Android UI Development: Tips, Tricks, and Techniques (20)

ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013ProTips DroidCon Paris 2013
ProTips DroidCon Paris 2013
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Action bar
Action barAction bar
Action bar
 
Creating custom views
Creating custom viewsCreating custom views
Creating custom views
 
Android Support Library
Android Support LibraryAndroid Support Library
Android Support Library
 
Jollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-levelJollen's Presentation: Introducing Android low-level
Jollen's Presentation: Introducing Android low-level
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
W-JAX 09 - Lift
W-JAX 09 - LiftW-JAX 09 - Lift
W-JAX 09 - Lift
 
Day 1
Day 1Day 1
Day 1
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animations
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Introduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R ShinyIntroduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R Shiny
 
Rubymotion talk
Rubymotion talkRubymotion talk
Rubymotion talk
 
Android 3
Android 3Android 3
Android 3
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03
 

Dernier

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Dernier (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Android UI Development: Tips, Tricks, and Techniques

  • 1. Android UI Development: Tips, Tricks, and Techniques Romain Guy Chet Haase Android UI Toolkit Team Google
  • 2. Android UI Development: rrific Tips,Tricks, and Techniques lly Te Tota Romain Guy Chet Haase Android UI Toolkit Team Google
  • 4. Trash Talk or Garbage Zero Avoid creating garbage, when necessary and possible
  • 5. Statics as Temporaries • Instead of a temporary object: public boolean pointInArea(int x, int y, Area area) { Point testPoint = new Point(x, y); return area.intersect(testPoint); } • Consider a static instead: static final Point tmpPoint = new Point(); public boolean pointInArea(int x, int y, Area area) { tmpPoint.x = x; tmpPoint.y = y; return area.intersect(tmpPoint.yPoint); } 5
  • 6. AutoBoxing • Autoboxing creates Objects float x = 5; Float y = x; doSomething(x); void doSomething(Float z) {} is equivalent to float x = 5; Float y = new Float(x); doSomething(new Float(x)); void doSomething(Float z) {} 6
  • 7. De-Autoboxing • Use primitive types whenever possible –Avoids Object creation • Use types you need for the situation –Avoids autoboxing back and forth 7
  • 8. Obliterator • The enhanced for() loop is great • ... but creates garbage for (Node node : nodeList) {} is equivalent to Iterator iter = nodeList.iterator(); while (iter.hasNext()) {} • Consider a size check first: if (nodeList.size() > 0) { for (Node node : nodeList) {} } 8
  • 9. Image is Everything • Recycle those Bitmaps –Device resources are limited • Finalizers will clear them ... eventually • You might think this would help // done using this one, clear reference myBitmap = null; • But you really want to do this // done using this one, recycle it myBitmap.recycle(); • Don’t wait for the finalizer to do the work if you need that memory now 9
  • 10. Varargh • Parameters to varargs method packaged into a temporary array void someMethod(float... args) {} someMethod(5f); is equivalent to someMethod(new float[]{5}); 10
  • 11. Gener-ick • T doesn’t stand for “primitive Type” public class MyClass<T> { T myVar; MyClass<T>(T arg) { myVar = arg; } } • Generics only deal with Objects; primitive types get autoboxed float f; MyClass<Float> myObject = new MyClass<Float>(f); which is equivalent to MyClass<Float> myObject = new MyClass<Float>(new Float(f)); 11
  • 12. Tools: Allocation Tracking • Limit allocations to find problems int prevLimt = -1; try { prevLimit = Debug.setAllocationLimit(0); // Do stuff } finally { Debug.setAllocationLimit(-1); } • Count the allocations being made Debug.startAllocationCounting(); // do stuff int allocCount = Debug.getThreadAllocCount(); Debug.stopAllocationCounting); 12
  • 13. Tools: DDMS • Visual tool helps track allocations down to the object/file/line number • (demo) 13
  • 14. Watch the Garbage... But Don’t Be Silly • As Michael Abrash might have said: ViewRoot –“Premature optimization is the Root of all evil” • Minor garbage is irrelevant in most cases • But if you have GCs at critical points in your application, consider Garbage Zero –Example: animations 14
  • 15. Tools: hat • DDMS • Heap Analysis Tool is used to track down memory leaks • adb shell dumpsys meminfo <process> 15
  • 16. Memory leaks • Be careful with Context • Be careful with static fields • Avoid non-static inner classes • Use weak references 16
  • 18. Responsiveness • Single-threaded UI • Don’t block the UI thread – Also called main thread • AsyncTask – Worker thread and UI thread messaging • Handler – Messaging 18
  • 19. Overinvalidating • Only redraw what you must • (demo) 19
  • 20. Fewer is better • Many views – Slower layout – Slower drawing – Slower startup time • Deep hierarchies – Memory – Slow... – StackOverflowException 20
  • 22. Layout optimizations • Custom views • Custom layouts • <merge /> • ViewStub • Compound drawables • layoutopt 22
  • 23. ViewStub 23
  • 24. ViewStub 24
  • 25. ViewStub <ViewStub android:id="@+id/stub_import" android:inflatedId="@+id/panel_import" android:layout="@layout/progress_overlay" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> 25
  • 26. ViewStub findViewById(R.id.stub_import).setVisibility(View.VISIBLE); // or View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate(); 26
  • 27. <merge/> 27
  • 28. <merge/> <!-- The merge tag must be the root tag --> <merge xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Content --> </merge> 28
  • 29. Compound drawables <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> 29
  • 30. Compound drawables <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello" android:drawableLeft="@drawable/icon" /> 30
  • 32. ListView 1 public View getView(int position, View convertView, ViewGroup parent) { 2 View item = mInflater.inflate(R.layout.list_item_icon_text, null); 3 ((TextView) item.findViewById(R.id.text)).setText(DATA[position]); 4 ((ImageView) item.findViewById(R.id.icon)).setImageBitmap( 5 (position & 1) == 1 ? mIcon1 : mIcon2); 6 return item; 7 } 32
  • 33. ListView 1 public View getView(int position, View convertView, ViewGroup parent) { 2 if (convertView == null) { 3 convertView = mInflater.inflate(R.layout.item, parent, false); 4 } 5 ((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]); 6 ((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap( 7 (position & 1) == 1 ? mIcon1 : mIcon2); 8 return convertView; 9 } 33
  • 34. ListView static class ViewHolder { TextView text; ImageView icon; } 34
  • 35. ListView 1 public View getView(int position, View convertView, ViewGroup parent) { 2 ViewHolder holder; 3 4 if (convertView == null) { 5 convertView = mInflater.inflate(R.layout.list_item_icon_text, 6 parent, false); 7 holder = new ViewHolder(); 8 holder.text = (TextView) convertView.findViewById(R.id.text); 9 holder.icon = (ImageView) convertView.findViewById(R.id.icon); 10 11 convertView.setTag(holder); 12 } else { 13 holder = (ViewHolder) convertView.getTag(); 14 } 15 16 holder.text.setText(DATA[position]); 17 holder.icon.setImageBitmap((position & 1) ==? mIcon1 : mIcon2); 18 19 return convertView; 20 } 35
  • 36. ListView 60.0 50.0 40.0 30.0 20.0 10.0 0 Dumb Correct Fast List of 10,000 items on NexusOne, Android 2.2 36
  • 37. Graphics optimizations • Pre-scale bitmaps • Use compatible bitmaps – ARGB_8888 to draw on 32 bits window • Avoid blending • Use View drawing caches – View.setDrawingCacheEnabled(true) • View.isOpaque() 37
  • 38. For More Information • Android developer site –developer.android.com • Romain –@romainguy –curious-creature.org • Chet –@chethaase –graphics-geek.blogspot.com 38