SlideShare una empresa de Scribd logo
1 de 48
Descargar para leer sin conexión
Custom UI Components
 
Widgets and Layouts are
used to construct a UI.
• A Widget is a UI element, like a text field or button
• Layouts are invisible containers, like LinearLayout or
  RelativeLayout
Widget != Widget
Widget
Layout
View Hierarchy
Why build custom
components? Isn't
there enough already?
Free
37 SEK
public void onCreate(Bundle savedInstanceState) {
    ....
    mPriceTextView = (TextView) findViewById(R.id.price);
    mPriceTextView.addTextChangedListener(new TextWatcher() {
         @Override
         public void onTextChanged(CharSequence s, int start,
                 int before, int count) {
             if (getText(R.string.free).equals(s.toString())) {
                 mPriceTextView.setTextColor(
                     getResources().getColor(R.color.free));
             } else {
                 mPriceTextView.setTextColor(
                     getResources().getColor(R.color.rent));
             }
         }

          @Override
          public void beforeTextChanged(CharSequence s, int start,
                  int count, int after) { }

          @Override
          public void afterTextChanged(Editable s) { }
    });
}
We can solve this
problem with custom
components.
When building a fully
customized component
extend View.
Need to override onDraw
to be able to show
something.
•   2D graphics
•   Text in different variations
•   Other components
•   Or pretty much anything else
onMeasure should be
overridden by subclasses
to provide measurement
of their contents.
Custom widgets can
really be as complicated
as you need them to be.
Not so fully customized
components.
PriceView
public class PriceView extends TextView implements TextWatcher {

    public PriceView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onTextChanged(CharSequence s, int start,
            int before, int count) {
        if (!TextUtils.isEmpty(s) && getResources()
                .getText(R.string.free).equals(s.toString())) {
            setTextColor(getResources().getColor(R.color.free));
        } else {
            setTextColor(getResources().getColor(R.color.rent));
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start,
            int count, int after) {
    }
}
<TextView 
    android:id="@+id/price"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/free"
    android:textSize="30sp"
    />

<com.markupartist.demo.ao11.demo2.PriceView 
    android:id="@+id/price"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/free"
    android:textSize="30sp"
    />
Demo
  
Compound Components




 priceView.setPrice(
     new Price(amount, currency)
 );
 
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    <TextView
        android:id="@+id/amount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/rent"
        android:textSize="30sp"
        />
    <TextView
        android:id="@+id/currency"
        android:paddingLeft="5dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        />
</LinearLayout>
public class PriceView extends LinearLayout {
    private TextView mAmount;
    private TextView mCurrency;
    public PriceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout priceView = (LinearLayout) inflater.inflate(
                R.layout.priceview, null);
        mAmount = (TextView) priceView.findViewById(R.id.amount);
        mCurrency = (TextView) priceView.findViewById(R.id.currency);
    }
    public void setPrice(Price price) {
        mAmount.setText(price.getAmount());
        mCurrency.setText(price.getCurrency());
    }
}
Demo
  
How to debug and
optimize the UI?
$ ./tools/layoutopt
$ ./tools/hierarchyviewer
Demo
Hiearchy Viewer
Reduce the number of
views in the view tree
with <merge>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/amount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/rent"
        android:textSize="30sp"/>
    <TextView
        android:id="@+id/currency"
        android:paddingLeft="5dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"/>
</LinearLayout>
<merge
    <TextView
         android:id="@+id/amount"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textColor="@color/rent"
         android:textSize="30sp"/>
    <TextView
         android:id="@+id/currency"
         android:paddingLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textSize="30sp"/>
</merge>
And...

inflater.inflate(
    R.layout.priceview,
    null
    this,
);
    true
);
Demo
Hiearchy Viewer
isInEditMode()
 
Photo by anarchosyn, http://www.flickr.com/photos/24293932@N00/4530523480/
Sets of properties that specifies the
look of a Widget. This can be
properties such a width, height and
colors. The concept is similar to
CSS and separates presentation
from the content.
Styles and Themes
• Custom attributes
• Styles
• Themes
Custom attributes
<com.markupartist.demo.ao11.demo5.PriceView
    android:id="@+id/price"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:amountText="37"
    app:currencyText="SEK"
    />
Goes into
res/values/attrs.xml
• Declared in the top <resources or in the <declare-stylable>
  element
• The <attr> element has two attributes name and format
   – Name is used when referring from code e.g.
     R.stylable.PriceView_amountText
   – Format defines the value it represents
      •   Reference
      •   Color
      •   String
      •   Boolean
      •   And a few more
Custom Attributes
<resources>
    <attr name="amountStyle" format="reference" />
    <declare-styleable name="PriceView">
        <attr name="amountText" format="string" />
    </declare-styleable>
</resources>

public PriceView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray array = context.obtainStyledAttributes(
        attrs, R.styleable.PriceView, 0, 0);
    String amountText =
        array.getString(R.styleable.PriceView_amountText);
    // Set amount to the view...
    array.recycle();
}
Styles goes into
res/values/styles.xml
<merge>
    <TextView android:id="@+id/amount" style="@style/AmountText"/>
    <TextView android:id="@+id/currency" style="@style/CurrencyText"/>
</merge>

<style name="PriceText" parent="android:style/Widget.TextView">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textSize">30sp</item>
</style>

<style name="AmountText" parent="@style/PriceText">
    <item name="android:textColor">@color/rent</item>
</style>

<style name="CurrencyText" parent="@style/PriceText">
    <item name="android:paddingLeft">5dip</item>
</style>
A problem with styles is
that it's hard to change
the style of an View
that's included within a
compound component.
And we can't change the
style in runtime.
Themes, a style that’s
 applied to a whole
 Activity or Application
• With custom attributes we can provide a way to
  style views within compound components
• Makes it easier for others to override default styles
• This can be hooks for styles, dimensions, colors...
<attr name="amountStyle" format="reference" />

<TextView android:id="@+id/priceview_amount"
  style="?attr/amountStyle" />

<style name="AO11Theme" parent="android:style/Theme">
  <item name="amountStyle">@style/AmountText</item>
</style>

android:theme="@style/AO11Theme"

<style name="AO11ThemeCustom"
       parent="android:style/Theme.Light">
  <item name="amountStyle">@style/CustomAmountText</item>
</style>

android:theme="@style/AO11ThemeCustom"
How do we make a custom
component available for
other applications.
• We can't use JAR
• We don't want to copy-paste resources
Library Projects
• Holds shared code and resources
• Resources are merged at build time
• Can be used for
  – Custom components
  – White label apps
  – Paid and free versions of the same app
Thank you

https://github.com/johannilsson/ao11

Más contenido relacionado

Similar a Custom UI Components at Android Only 2011

Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
Big Data for each one of us
Big Data for each one of usBig Data for each one of us
Big Data for each one of us
OSCON Byrum
 
Responsive mobile design in practice
Responsive mobile design in practiceResponsive mobile design in practice
Responsive mobile design in practice
Kirill Grouchnikov
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
Vlad Kolesnyk
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
Vlad Kolesnyk
 

Similar a Custom UI Components at Android Only 2011 (20)

Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
Android 2
Android 2Android 2
Android 2
 
Big Data for each one of us
Big Data for each one of usBig Data for each one of us
Big Data for each one of us
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
 
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
 
Responsive mobile design in practice
Responsive mobile design in practiceResponsive mobile design in practice
Responsive mobile design in practice
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
 
Android 3
Android 3Android 3
Android 3
 
Android Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection WidgetAndroid Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection Widget
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)
 
Android crashcourse
Android crashcourseAndroid crashcourse
Android crashcourse
 
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
 
What's New in Android
What's New in AndroidWhat's New in Android
What's New in Android
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenesAcademy PRO: React native - building first scenes
Academy PRO: React native - building first scenes
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdf
 
Knockoutjs UG meeting presentation
Knockoutjs UG meeting presentationKnockoutjs UG meeting presentation
Knockoutjs UG meeting presentation
 

Más de Johan Nilsson

Más de Johan Nilsson (11)

Utmaningar som tredjepartsutvecklare för kollektivtrafikbranchen - Kollektivt...
Utmaningar som tredjepartsutvecklare för kollektivtrafikbranchen - Kollektivt...Utmaningar som tredjepartsutvecklare för kollektivtrafikbranchen - Kollektivt...
Utmaningar som tredjepartsutvecklare för kollektivtrafikbranchen - Kollektivt...
 
GTFS & OSM in STHLM Traveling at Trafiklab
GTFS & OSM in STHLM Traveling at Trafiklab GTFS & OSM in STHLM Traveling at Trafiklab
GTFS & OSM in STHLM Traveling at Trafiklab
 
STHLM Traveling Trafiklab
STHLM Traveling TrafiklabSTHLM Traveling Trafiklab
STHLM Traveling Trafiklab
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & Browserify
 
Spacebrew & Arduino Yún
Spacebrew & Arduino YúnSpacebrew & Arduino Yún
Spacebrew & Arduino Yún
 
Trafiklab 1206
Trafiklab 1206Trafiklab 1206
Trafiklab 1206
 
new Android UI Patterns
new Android UI Patternsnew Android UI Patterns
new Android UI Patterns
 
FOSS STHLM Android Cloud to Device Messaging
FOSS STHLM Android Cloud to Device MessagingFOSS STHLM Android Cloud to Device Messaging
FOSS STHLM Android Cloud to Device Messaging
 
Android Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG StockholmAndroid Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG Stockholm
 
Android swedroid
Android swedroidAndroid swedroid
Android swedroid
 
GTUG Android iglaset Presentation 1 Oct
GTUG Android iglaset Presentation 1 OctGTUG Android iglaset Presentation 1 Oct
GTUG Android iglaset Presentation 1 Oct
 

Último

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
Safe Software
 
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
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
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
Victor Rentea
 

Último (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
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
 
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
 
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
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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)
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 

Custom UI Components at Android Only 2011