SlideShare a Scribd company logo
1 of 20
Views and Layout
Views and Layout
The Android platform provides the developer View and
ViewGroup to create graphical interfaces of the Activity.
A ViewGroup is a layout object that can contain other Views.
A GUI is composed of a hierarchy of ViewGroups and Views.
GUIs can be created with xml layout files, but can also be created
at runtime because the xml file is a tool to simplify the job of the
developer: all xml file are parsed at runtime to create the objects
related with the listed attributes. This system is flexible to declare
different layouts for different configurations that would otherwise
be handled by code.
Views and Layout
Views and Layout
To indicate to the Activity which xml layout file in the /res folder
must be loaded you can use the method:
Activity.setContentView(int resourceId)
To retrieve an instance of a layout object the following method is
available:
Activity.findViewById(int resourceId)
Pattern: The invocation of setContentView() is free and can be
done at any point in the life cycle of the Activity. However, to
respect the time of parsing and to make the system to instantiate
all classes View contained once it is preferable to invoke it and
retrieve all View in onCreate().
UI Handling
Views and Layout
Each View or ViewGroup declared in the layout inherites from the
superclass attributes and specific attributes. The namespace is
always Android and the node is the name of the class you want to
instantiate.
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text" />
The difference between View and ViewGroup on a .xml is the
ability to insert other View or ViewGroup within the node of a
ViewGroup.
In general, the attributes that must always be specified are:
android:layout_width
android:layout_height
Attributes
Views and Layout
android:layout_width
android:layout_height
The parameters accepted by these attributes are:
● wrap_content
● fill_parent (match_parent)
● A value with relative units of measurement
● A reference to a dimen object
The id attribute is used to retrieve the instance of the View or
ViewGroup at runtime or in other positions of the layout.
To indicate to the system that a new entry is to be created in R
class for the view to be identified elsewhere you need to use this
syntax:
android:id=“@+id/<resourse_name>“
Attributes
Views and Layout
ViewGroups are:
● LinearLayout: the view contained are arranged in sequence
according to the indicated orientation attribute:
● android:orientation:"horizontal (default)
● vertical
● RelativeLayout: Each view can contain information about the
relative position to other already declared View or ViewGroup:
● layout_below
● layout_above
● layout_toRightOf
● layout_toLeftOf
● layout_alignParentTop
● layout_alignParentBottom
● layout_alignParentRight
● layout_alignParentLeft
Main Layouts
Views and Layout
● ScrollView: it allows vertical scrolling content. To do this it
accepts one only View or ViewGroup (which may contain other
View and ViewGroup)
● HorizontalScrollView: it allows horizontal scrolling of the
content. To do this it accepts one only View or ViewGroup
(which may contain other View and ViewGroup)
● ListView e GridView: they allow vertical scrolling of View and
ViewGroup. Entry must be done at runtime with an Adapter
object which must be specified in the id of the layout to be
loaded for each element.
● RadioGroup: it contains RadioButtons of which only one
element is checked
● TableLayout: it contains TableRow for creating a table.
Main Layouts
Views and Layout
● TextView
● EditText
● Button
● ImageView
● CheckBox
● ImageButton
● ProgressView
● RadioButton
● RatingBar
● SeekBar
● Spinner
● TextClock
● TimePicker
● DatePicker
● ToggleButton
Main View
● VideoView
● MediaController
● CheckedTextView
● AutoCompleteTextView
● CalendarView
● Chronometer
● DigitalClock
● ImageSwitcher
● NumberPicker
● SlidingDrawer
● ViewAnimator
● ViewSwitcher
● ViewFlipper
● ViewStub
● WebView
Views and Layout
Events are managed by implementing the interfaces of the
classes or superclasses that extends View.
The View class provides the following interfaces:
● View.OnClickListener{onClick(View v)} to handle the simple
click.
● View.onLongClickListener { onLongClick(View v) } o handle a
long click.
● View.onTouchListener { onTouch(View v, MotionEvent e) } to
handle a generic touch event
The implementation of the interface is passed to the View with the
methods:
View.setOnClickListener(View.OnClickListener listener)
View.setOnLongClickListener(View.OnLongClickListener listener)
View.setOnTouchListener(View.OnTouchListener listener)
Event Handlers
Views and Layout
There are 2 ways to implement the interfaces:
● Anonymous implementation:
private OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
// ...
}
};
● Implementation as part of the Activity:
public class ExampleActivity extends Activity implements OnClickListener {
public void onClick(View v) {
// ...
}
}
Event handlers
Views and Layout
The implementation of anonymous is the most widely used, but it
produces overload of classes instantiated and allocation of
objects.
Pattern: it is preferable to implement the management of the
events as an integral part of the Activity not only to the
advantages in the management of the memory, but also for the
readability of the code (to avoid multiple indentations and to have
just one method that handles the events of all the Views).
Centralized management is possible by checking if the event was
generated by a View through its id:
public void onClick(View v) {
switch (v.getId()) {
case R.id.example:
// ...
break;
}
}
Event Handlers
Views and Layout
All Android Views extend the View class, and then to create a
custom view the class must extend View.
If you want to implement a new functionality for an existing View
you can extended directly that class.
Ex. To create a button that changes the background in certain
states you can extend Button instead redefine all its methods by
extending View
To create custom view you need to put the right emphasis on the
use of memory and CPU.
Custom View
Views and Layout
All the custom view created in xml file can be inserted as part of
the graphical interface. The node to be specified must contain the
complete package in addition to the name of the class in this way:
<com.example.android.view.CustomView ... />
The attributes that you can specify are those inherited from the
superclass and custom ones defined by the developer.
The definition of the attributes is via custom xml in the res/values
folder (in a file usually called attrs.xml)
<resources>
<declare-styleable name="CustomView" >
<attr name="showText" format="boolean" />
<attr name="labelPosition" format="enum" >
<enum name="left" value="0" />
<enum name="right" value="1" />
</attr>
</declare-styleable>
</resources>
Custom View - Attributes
Views and Layout
To insert the custom attributes inside the layout xml file you need
to add a namespace:
xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews"
Or try making the system automatically in case of multiple custom
views in the same layout:
xmlns:custom="http://schemas.android.com/apk/res-auto"
The alias is chosen by the developer.
Custom View - Attributes
Views and Layout
Each custom view must implement at least one of the three
constructors inherited from the superclass View:
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int
defStyleAttr) {
super(context, attrs, defStyleAttr);
}
Custom View - Constructor
Views and Layout
To retrieve custom attributes defined in the layout you can use a
TypedArray object with the AttributeSet passed by the
constructor:
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.CustomView, 0, 0);
try {
showText = a.getBoolean(R.styleable.CustomView_showText,
false);
textPos = a.getInteger(R.styleable.CustomView_labelPosition, 0);
} finally {
a.recycle();
}
}
Custom View – Attributes
Retrieving
Views and Layout
The recovery of custom attributes is static. To make it dynamic fit
getter and setter methods for each attribute that you want to
manage externally:
public boolean isShowText() {
return showText;
}
public void setShowText(boolean showText) {
this.showText = showText;
invalidate();
requestLayout();
}
The View.invalidate() method completely redraws the view in
order to apply the change immediately.
The View.requestLayout() method notifies the layout that contains
the view that you have changed the size of its View.
Custom View – Attributes
management
Views and Layout
The View.onDraw() method specifies how to bring up the View. It
uses an object:
● Canvas: to determine what and where to draw;
● Paint: to determine how to draw.
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (showText) {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawText(text, x, y, paint);
}
}
Custom View – onDraw()
Views and Layout
The View.onMeasure() method recovers the size of the View
requests from ViewGroup that contains it. In this way you can
calculate the correct size for the View in a variety of layouts,
configurations, display resolutions of the device.
@Override
protected void onMeasure(int widthMeasureSpec, int
heightMeasureSpec) {
int minw = getPaddingLeft() + getPaddingRight()
+ getSuggestedMinimumWidth();
int w = resolveSizeAndState(minw, widthMeasureSpec, 1);
int minh = MeasureSpec.getSize(w) - (int) mTextWidth
+ getPaddingBottom() + getPaddingTop();
int h = resolveSizeAndState(MeasureSpec.getSize(w) -
(int) mTextWidth,
heightMeasureSpec, 0);
setMeasuredDimension(w, h);
}
Custom View – onMeasure()
Views and Layout
The main aspects to be considered in designing a custom view are:
● The method of the View that has the greatest load on the Main
Thread of the application is the View.onDraw() method.
● The View.requestLayout() method generates a call to cascade to the
entire hierarchy of View contained in the layout.
● The View.invalidate() method call results in a new View.onDraw()
Pattern: so that the view will be seamless and not impact the loading of the
other view,
● It must minimize the call to the methods View.invalidate() and
View.requestLayout().
● The animations are handled externally with the objects available for the
purpose and not in the method View.onDraw().
● In order not to overload the method View.onDraw () is necessary not to
instantiate objects in its implementation, but only during the creation of the
View.
Custom View – Optimization

More Related Content

What's hot (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
 
List Views
List ViewsList Views
List Views
 
Lab2-android
Lab2-androidLab2-android
Lab2-android
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Backendless apps
Backendless appsBackendless apps
Backendless apps
 
Android adapters
Android adaptersAndroid adapters
Android adapters
 
Android ui layout
Android ui layoutAndroid ui layout
Android ui layout
 
Lab3-Android
Lab3-AndroidLab3-Android
Lab3-Android
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and Activity
 
Android xml-based layouts-chapter5
Android xml-based layouts-chapter5Android xml-based layouts-chapter5
Android xml-based layouts-chapter5
 
Lab 5-Android
Lab 5-AndroidLab 5-Android
Lab 5-Android
 
Android components
Android componentsAndroid components
Android components
 
Develop a native application that uses GPS location.pptx
Develop a native application that uses GPS location.pptxDevelop a native application that uses GPS location.pptx
Develop a native application that uses GPS location.pptx
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & Intents
 
Android Widget
Android WidgetAndroid Widget
Android Widget
 
android layouts
android layoutsandroid layouts
android layouts
 
SQL Programming
SQL ProgrammingSQL Programming
SQL Programming
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 

Viewers also liked

Android chapter01-intro
Android chapter01-introAndroid chapter01-intro
Android chapter01-introCouhp HD
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsAndroid App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsDiego Grancini
 
Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsDiego Grancini
 
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)Nanik Tolaram
 
Analizamos 19 plataformas de eLearning: primera investigación académica colab...
Analizamos 19 plataformas de eLearning: primera investigación académica colab...Analizamos 19 plataformas de eLearning: primera investigación académica colab...
Analizamos 19 plataformas de eLearning: primera investigación académica colab...Conectarnos Soluciones de Internet
 
How To Get Real ROI From Social Media for Jewelers
How To Get Real ROI From Social Media for JewelersHow To Get Real ROI From Social Media for Jewelers
How To Get Real ROI From Social Media for JewelersDave Kerpen
 

Viewers also liked (8)

Android chapter01-intro
Android chapter01-introAndroid chapter01-intro
Android chapter01-intro
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsAndroid App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
 
Chapter 15 power point
Chapter 15 power pointChapter 15 power point
Chapter 15 power point
 
Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notifications
 
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
 
Analizamos 19 plataformas de eLearning: primera investigación académica colab...
Analizamos 19 plataformas de eLearning: primera investigación académica colab...Analizamos 19 plataformas de eLearning: primera investigación académica colab...
Analizamos 19 plataformas de eLearning: primera investigación académica colab...
 
How To Get Real ROI From Social Media for Jewelers
How To Get Real ROI From Social Media for JewelersHow To Get Real ROI From Social Media for Jewelers
How To Get Real ROI From Social Media for Jewelers
 
Android ppt
Android ppt Android ppt
Android ppt
 

Similar to Android App Development - 04 Views and layouts

07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdfImranS18
 
Android Custom views
Android Custom views   Android Custom views
Android Custom views Matej Vukosav
 
Android apps development
Android apps developmentAndroid apps development
Android apps developmentMonir Zzaman
 
Android Tutorial
Android TutorialAndroid Tutorial
Android TutorialFun2Do Labs
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfacesC.o. Nieto
 
iOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsiOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsAsim Rais Siddiqui
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView ScrollingAndrea Prearo
 
Building a simple user interface lesson2
Building a simple user interface lesson2Building a simple user interface lesson2
Building a simple user interface lesson2Kalluri Vinay Reddy
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android AppsGil Irizarry
 
Lecture 2 Styling and Layout in React Native.pptx
Lecture 2 Styling and Layout in React Native.pptxLecture 2 Styling and Layout in React Native.pptx
Lecture 2 Styling and Layout in React Native.pptxGevitaChinnaiah
 
Android Custom Views
Android Custom ViewsAndroid Custom Views
Android Custom ViewsBabar Sanah
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Johan Nilsson
 
Android development for iOS developers
Android development for iOS developersAndroid development for iOS developers
Android development for iOS developersDarryl Bayliss
 
Yii in action
Yii in actionYii in action
Yii in actionKeaNy Chu
 

Similar to Android App Development - 04 Views and layouts (20)

Advance RCP
Advance RCPAdvance RCP
Advance RCP
 
08ui.pptx
08ui.pptx08ui.pptx
08ui.pptx
 
Hello Android
Hello AndroidHello Android
Hello Android
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdf
 
Android Custom views
Android Custom views   Android Custom views
Android Custom views
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
Android Tutorial
Android TutorialAndroid Tutorial
Android Tutorial
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfaces
 
iOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI ComponentsiOS Development (Part 3) - Additional GUI Components
iOS Development (Part 3) - Additional GUI Components
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView Scrolling
 
Building a simple user interface lesson2
Building a simple user interface lesson2Building a simple user interface lesson2
Building a simple user interface lesson2
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android Apps
 
Custom components
Custom componentsCustom components
Custom components
 
Actionview
ActionviewActionview
Actionview
 
Android 3
Android 3Android 3
Android 3
 
Lecture 2 Styling and Layout in React Native.pptx
Lecture 2 Styling and Layout in React Native.pptxLecture 2 Styling and Layout in React Native.pptx
Lecture 2 Styling and Layout in React Native.pptx
 
Android Custom Views
Android Custom ViewsAndroid Custom Views
Android Custom Views
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011
 
Android development for iOS developers
Android development for iOS developersAndroid development for iOS developers
Android development for iOS developers
 
Yii in action
Yii in actionYii in action
Yii in action
 

More from Diego Grancini

Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsDiego Grancini
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animationsDiego Grancini
 
Android App Development - 10 Content providers
Android App Development - 10 Content providersAndroid App Development - 10 Content providers
Android App Development - 10 Content providersDiego Grancini
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 StorageDiego Grancini
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 ServicesDiego Grancini
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 ThreadingDiego Grancini
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 FragmentsDiego Grancini
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action barDiego Grancini
 
Android App Development - 03 Resources
Android App Development - 03 ResourcesAndroid App Development - 03 Resources
Android App Development - 03 ResourcesDiego Grancini
 
Android App Development - 01 Introduction
Android App Development - 01 IntroductionAndroid App Development - 01 Introduction
Android App Development - 01 IntroductionDiego Grancini
 

More from Diego Grancini (10)

Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgets
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animations
 
Android App Development - 10 Content providers
Android App Development - 10 Content providersAndroid App Development - 10 Content providers
Android App Development - 10 Content providers
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 Services
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action bar
 
Android App Development - 03 Resources
Android App Development - 03 ResourcesAndroid App Development - 03 Resources
Android App Development - 03 Resources
 
Android App Development - 01 Introduction
Android App Development - 01 IntroductionAndroid App Development - 01 Introduction
Android App Development - 01 Introduction
 

Android App Development - 04 Views and layouts

  • 2. Views and Layout The Android platform provides the developer View and ViewGroup to create graphical interfaces of the Activity. A ViewGroup is a layout object that can contain other Views. A GUI is composed of a hierarchy of ViewGroups and Views. GUIs can be created with xml layout files, but can also be created at runtime because the xml file is a tool to simplify the job of the developer: all xml file are parsed at runtime to create the objects related with the listed attributes. This system is flexible to declare different layouts for different configurations that would otherwise be handled by code. Views and Layout
  • 3. Views and Layout To indicate to the Activity which xml layout file in the /res folder must be loaded you can use the method: Activity.setContentView(int resourceId) To retrieve an instance of a layout object the following method is available: Activity.findViewById(int resourceId) Pattern: The invocation of setContentView() is free and can be done at any point in the life cycle of the Activity. However, to respect the time of parsing and to make the system to instantiate all classes View contained once it is preferable to invoke it and retrieve all View in onCreate(). UI Handling
  • 4. Views and Layout Each View or ViewGroup declared in the layout inherites from the superclass attributes and specific attributes. The namespace is always Android and the node is the name of the class you want to instantiate. <Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/my_button_text" /> The difference between View and ViewGroup on a .xml is the ability to insert other View or ViewGroup within the node of a ViewGroup. In general, the attributes that must always be specified are: android:layout_width android:layout_height Attributes
  • 5. Views and Layout android:layout_width android:layout_height The parameters accepted by these attributes are: ● wrap_content ● fill_parent (match_parent) ● A value with relative units of measurement ● A reference to a dimen object The id attribute is used to retrieve the instance of the View or ViewGroup at runtime or in other positions of the layout. To indicate to the system that a new entry is to be created in R class for the view to be identified elsewhere you need to use this syntax: android:id=“@+id/<resourse_name>“ Attributes
  • 6. Views and Layout ViewGroups are: ● LinearLayout: the view contained are arranged in sequence according to the indicated orientation attribute: ● android:orientation:"horizontal (default) ● vertical ● RelativeLayout: Each view can contain information about the relative position to other already declared View or ViewGroup: ● layout_below ● layout_above ● layout_toRightOf ● layout_toLeftOf ● layout_alignParentTop ● layout_alignParentBottom ● layout_alignParentRight ● layout_alignParentLeft Main Layouts
  • 7. Views and Layout ● ScrollView: it allows vertical scrolling content. To do this it accepts one only View or ViewGroup (which may contain other View and ViewGroup) ● HorizontalScrollView: it allows horizontal scrolling of the content. To do this it accepts one only View or ViewGroup (which may contain other View and ViewGroup) ● ListView e GridView: they allow vertical scrolling of View and ViewGroup. Entry must be done at runtime with an Adapter object which must be specified in the id of the layout to be loaded for each element. ● RadioGroup: it contains RadioButtons of which only one element is checked ● TableLayout: it contains TableRow for creating a table. Main Layouts
  • 8. Views and Layout ● TextView ● EditText ● Button ● ImageView ● CheckBox ● ImageButton ● ProgressView ● RadioButton ● RatingBar ● SeekBar ● Spinner ● TextClock ● TimePicker ● DatePicker ● ToggleButton Main View ● VideoView ● MediaController ● CheckedTextView ● AutoCompleteTextView ● CalendarView ● Chronometer ● DigitalClock ● ImageSwitcher ● NumberPicker ● SlidingDrawer ● ViewAnimator ● ViewSwitcher ● ViewFlipper ● ViewStub ● WebView
  • 9. Views and Layout Events are managed by implementing the interfaces of the classes or superclasses that extends View. The View class provides the following interfaces: ● View.OnClickListener{onClick(View v)} to handle the simple click. ● View.onLongClickListener { onLongClick(View v) } o handle a long click. ● View.onTouchListener { onTouch(View v, MotionEvent e) } to handle a generic touch event The implementation of the interface is passed to the View with the methods: View.setOnClickListener(View.OnClickListener listener) View.setOnLongClickListener(View.OnLongClickListener listener) View.setOnTouchListener(View.OnTouchListener listener) Event Handlers
  • 10. Views and Layout There are 2 ways to implement the interfaces: ● Anonymous implementation: private OnClickListener listener = new OnClickListener() { public void onClick(View v) { // ... } }; ● Implementation as part of the Activity: public class ExampleActivity extends Activity implements OnClickListener { public void onClick(View v) { // ... } } Event handlers
  • 11. Views and Layout The implementation of anonymous is the most widely used, but it produces overload of classes instantiated and allocation of objects. Pattern: it is preferable to implement the management of the events as an integral part of the Activity not only to the advantages in the management of the memory, but also for the readability of the code (to avoid multiple indentations and to have just one method that handles the events of all the Views). Centralized management is possible by checking if the event was generated by a View through its id: public void onClick(View v) { switch (v.getId()) { case R.id.example: // ... break; } } Event Handlers
  • 12. Views and Layout All Android Views extend the View class, and then to create a custom view the class must extend View. If you want to implement a new functionality for an existing View you can extended directly that class. Ex. To create a button that changes the background in certain states you can extend Button instead redefine all its methods by extending View To create custom view you need to put the right emphasis on the use of memory and CPU. Custom View
  • 13. Views and Layout All the custom view created in xml file can be inserted as part of the graphical interface. The node to be specified must contain the complete package in addition to the name of the class in this way: <com.example.android.view.CustomView ... /> The attributes that you can specify are those inherited from the superclass and custom ones defined by the developer. The definition of the attributes is via custom xml in the res/values folder (in a file usually called attrs.xml) <resources> <declare-styleable name="CustomView" > <attr name="showText" format="boolean" /> <attr name="labelPosition" format="enum" > <enum name="left" value="0" /> <enum name="right" value="1" /> </attr> </declare-styleable> </resources> Custom View - Attributes
  • 14. Views and Layout To insert the custom attributes inside the layout xml file you need to add a namespace: xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews" Or try making the system automatically in case of multiple custom views in the same layout: xmlns:custom="http://schemas.android.com/apk/res-auto" The alias is chosen by the developer. Custom View - Attributes
  • 15. Views and Layout Each custom view must implement at least one of the three constructors inherited from the superclass View: public CustomView(Context context) { super(context); } public CustomView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } Custom View - Constructor
  • 16. Views and Layout To retrieve custom attributes defined in the layout you can use a TypedArray object with the AttributeSet passed by the constructor: public CustomView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0); try { showText = a.getBoolean(R.styleable.CustomView_showText, false); textPos = a.getInteger(R.styleable.CustomView_labelPosition, 0); } finally { a.recycle(); } } Custom View – Attributes Retrieving
  • 17. Views and Layout The recovery of custom attributes is static. To make it dynamic fit getter and setter methods for each attribute that you want to manage externally: public boolean isShowText() { return showText; } public void setShowText(boolean showText) { this.showText = showText; invalidate(); requestLayout(); } The View.invalidate() method completely redraws the view in order to apply the change immediately. The View.requestLayout() method notifies the layout that contains the view that you have changed the size of its View. Custom View – Attributes management
  • 18. Views and Layout The View.onDraw() method specifies how to bring up the View. It uses an object: ● Canvas: to determine what and where to draw; ● Paint: to determine how to draw. @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (showText) { Paint paint = new Paint(); paint.setColor(Color.BLACK); canvas.drawText(text, x, y, paint); } } Custom View – onDraw()
  • 19. Views and Layout The View.onMeasure() method recovers the size of the View requests from ViewGroup that contains it. In this way you can calculate the correct size for the View in a variety of layouts, configurations, display resolutions of the device. @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth(); int w = resolveSizeAndState(minw, widthMeasureSpec, 1); int minh = MeasureSpec.getSize(w) - (int) mTextWidth + getPaddingBottom() + getPaddingTop(); int h = resolveSizeAndState(MeasureSpec.getSize(w) - (int) mTextWidth, heightMeasureSpec, 0); setMeasuredDimension(w, h); } Custom View – onMeasure()
  • 20. Views and Layout The main aspects to be considered in designing a custom view are: ● The method of the View that has the greatest load on the Main Thread of the application is the View.onDraw() method. ● The View.requestLayout() method generates a call to cascade to the entire hierarchy of View contained in the layout. ● The View.invalidate() method call results in a new View.onDraw() Pattern: so that the view will be seamless and not impact the loading of the other view, ● It must minimize the call to the methods View.invalidate() and View.requestLayout(). ● The animations are handled externally with the objects available for the purpose and not in the method View.onDraw(). ● In order not to overload the method View.onDraw () is necessary not to instantiate objects in its implementation, but only during the creation of the View. Custom View – Optimization