The document discusses creating custom components in Android. It explains that custom components can be created by extending the View class and overriding methods like onDraw() and onMeasure(). It provides guidelines for defining custom attributes, applying attributes in code, and adding properties and events to custom components. Creating fully customized components involves extending View, handling drawing and measurement, and responding to user interactions. The document also covers modifying existing widgets by subclassing them and overriding specific methods.
The document discusses software design patterns, including definitions, types (creational, behavioral, structural), components, benefits, and examples. It provides examples of patterns like facade, observer, decorator, state, strategy, template method, iterator, bridge, and singleton from both non-software (e.g. auction, vending machine) and software domains (Temple Run 2 game). For each pattern, it explains the concept, provides a non-software diagram, describes an implementation in Temple Run 2, and diagrams the software example. The patterns allow code reuse, extensibility, and flexibility to vary behaviors without changing interfaces.
This document provides instructions for disassembling a carburetor in 3 steps and 3.2 substeps:
1) Remove the carburetor and clean the outside.
2) Remove the bowl by unscrewing it and removing the floats and pivot bar.
3) Remove the mixing cover by unscrewing it and sliding it off.
Cautions are provided about gasoline being flammable and to wear gloves when working with gasoline.
This Arena tutorial aims to provide beginners with a guide to get started using Arena simulation software. It discusses installing Arena, describes the overall features and interface of Arena including the model window, modules, and project bar. It then provides a step-by-step example of building a simulation model of a single server queueing system, defining the necessary data and flowchart modules, setting the run conditions, running the simulation, and reviewing the output reports.
Procedure of animation in 3 d autodesk maya tools & techniquesijcga
At present time a new technique to approaches for producing computer animation by using software. It is introduced at university level as a text for under graduates and post graduates. It is also useful for those who want to become computer graphics programmers or animation professionals. It is newly introduced techniques in which anyone can create animation for game, education or for entertainment. It addresses the issue of computer-based animation which primarily deals with multiple 2 dimensional planes. This document concentrates on full 3D computer animation by using Autodesk Maya software which is latest for animation and identifies the useful methods and techniques to move objects in interesting ways. In present time many film makers uses it for creating cartoon character for characterize their visualization on screen. A lot of softwares are available in market which helps to create such kind of animation and effect with help of computer graphics.
The document provides information about iOS development using Objective-C and Auto Layout. It discusses the popularity of iOS and Objective-C, introduces Auto Layout constraints and visual format language for layout, and provides code examples for adding constraints in code and using visual formats. It also covers detecting and resolving ambiguous layouts, setting constraint priorities, and supporting multiple device orientations and localization using Auto Layout.
This document describes a technical graphic showcase project created by four students using free and open source tools. The project aimed to create an immersive gaming experience using Unreal Engine 4 and Blender at zero cost. Key aspects discussed include the environment design using custom landscape imports, menu and UI design using UMG, modeling using modifiers and sculpting tools in Blender, animation system in Unreal Engine, AI implementation using behavior trees, and lighting setup. The project achieved the goals of creating a quality game experience with the latest graphics technology while incurring no development costs.
The document provides an overview of advanced customization techniques in SolidWorks, including customizing tags, mouse gestures, shortcut bars, sheet metal gauge tables, the hole wizard, hole callouts, symbols, and more. Specific examples are given around modifying hole callouts to remove drill size from tapped holes, creating a custom sheet metal gauge table, and adding a new symbol for visual inspection. The presentation aims to expose attendees to customizable areas in SolidWorks and provide instructions to allow users to explore these customizations on their own.
The document provides instructions for a practical evaluation in AutoCAD. It details how to:
1) Create layers, blocks, and insert blocks to represent electronic components.
2) Use printing commands to set the printing area, scale, and orientation to generate drawings.
3) Students will be evaluated on their accuracy and speed in completing these AutoCAD tasks.
The document discusses software design patterns, including definitions, types (creational, behavioral, structural), components, benefits, and examples. It provides examples of patterns like facade, observer, decorator, state, strategy, template method, iterator, bridge, and singleton from both non-software (e.g. auction, vending machine) and software domains (Temple Run 2 game). For each pattern, it explains the concept, provides a non-software diagram, describes an implementation in Temple Run 2, and diagrams the software example. The patterns allow code reuse, extensibility, and flexibility to vary behaviors without changing interfaces.
This document provides instructions for disassembling a carburetor in 3 steps and 3.2 substeps:
1) Remove the carburetor and clean the outside.
2) Remove the bowl by unscrewing it and removing the floats and pivot bar.
3) Remove the mixing cover by unscrewing it and sliding it off.
Cautions are provided about gasoline being flammable and to wear gloves when working with gasoline.
This Arena tutorial aims to provide beginners with a guide to get started using Arena simulation software. It discusses installing Arena, describes the overall features and interface of Arena including the model window, modules, and project bar. It then provides a step-by-step example of building a simulation model of a single server queueing system, defining the necessary data and flowchart modules, setting the run conditions, running the simulation, and reviewing the output reports.
Procedure of animation in 3 d autodesk maya tools & techniquesijcga
At present time a new technique to approaches for producing computer animation by using software. It is introduced at university level as a text for under graduates and post graduates. It is also useful for those who want to become computer graphics programmers or animation professionals. It is newly introduced techniques in which anyone can create animation for game, education or for entertainment. It addresses the issue of computer-based animation which primarily deals with multiple 2 dimensional planes. This document concentrates on full 3D computer animation by using Autodesk Maya software which is latest for animation and identifies the useful methods and techniques to move objects in interesting ways. In present time many film makers uses it for creating cartoon character for characterize their visualization on screen. A lot of softwares are available in market which helps to create such kind of animation and effect with help of computer graphics.
The document provides information about iOS development using Objective-C and Auto Layout. It discusses the popularity of iOS and Objective-C, introduces Auto Layout constraints and visual format language for layout, and provides code examples for adding constraints in code and using visual formats. It also covers detecting and resolving ambiguous layouts, setting constraint priorities, and supporting multiple device orientations and localization using Auto Layout.
This document describes a technical graphic showcase project created by four students using free and open source tools. The project aimed to create an immersive gaming experience using Unreal Engine 4 and Blender at zero cost. Key aspects discussed include the environment design using custom landscape imports, menu and UI design using UMG, modeling using modifiers and sculpting tools in Blender, animation system in Unreal Engine, AI implementation using behavior trees, and lighting setup. The project achieved the goals of creating a quality game experience with the latest graphics technology while incurring no development costs.
The document provides an overview of advanced customization techniques in SolidWorks, including customizing tags, mouse gestures, shortcut bars, sheet metal gauge tables, the hole wizard, hole callouts, symbols, and more. Specific examples are given around modifying hole callouts to remove drill size from tapped holes, creating a custom sheet metal gauge table, and adding a new symbol for visual inspection. The presentation aims to expose attendees to customizable areas in SolidWorks and provide instructions to allow users to explore these customizations on their own.
The document provides instructions for a practical evaluation in AutoCAD. It details how to:
1) Create layers, blocks, and insert blocks to represent electronic components.
2) Use printing commands to set the printing area, scale, and orientation to generate drawings.
3) Students will be evaluated on their accuracy and speed in completing these AutoCAD tasks.
The document discusses Android's windowing system architecture and components. It describes the main components as SurfaceManager, WindowManager, and ActivityManager. SurfaceManager is responsible for compositing surfaces. WindowManager creates and lays out surfaces on behalf of clients and dispatches input events. ActivityManager manages activity lifecycles and stacking. The document also covers handling gestures, animations, custom view architecture, using the hierarchy viewer tool, and event propagation in Android views.
This document discusses creating custom views in Android. It covers default views provided by Android, reasons for creating custom views, the responsibilities of views, and how to create custom views by extending the View class and implementing key methods like onDraw(), onMeasure(), and onLayout(). It also discusses compound views, view lifecycles, defining custom attributes, and using custom views in layout files.
The document discusses several design patterns including Iterator, Observer, Strategy, Composite, and Decorator. It provides examples of each pattern and explains the key ideas and benefits of using design patterns, such as allowing reusable and flexible designs that can be communicated through a common vocabulary.
The document discusses several design patterns including Iterator, Observer, Strategy, Composite, and Decorator. It provides examples of each pattern and explains the key ideas and benefits of using design patterns, such as creating reusable and flexible designs that can be communicated effectively.
Presentation about Android custom views held on 05.04.2018 on Infinum Android Talks
Code: https://github.com/MatejVukosav/ConceptView
Event:
https://www.facebook.com/events/626682637663384/
https://infinum.co/our-stuff/android-talks/29
Android App Development - 04 Views and layoutsDiego Grancini
The document discusses views and layouts in Android. It covers the View and ViewGroup classes used to create graphical interfaces. Layouts can be defined in XML files and include common layouts like LinearLayout, RelativeLayout, and ScrollView. It also discusses how to create custom views by extending the View class and implementing common callback methods like onDraw(), onMeasure(), and event handlers. Optimizing custom views to minimize calls to methods like invalidate() and requestLayout() is also covered.
This document discusses the evolution of graphical user interface (GUI) capabilities in the Java programming language. It describes the Abstract Window Toolkit (AWT) introduced in JDK 1.0, which provided basic cross-platform GUI functionality but had limitations. JDK 1.1 improved on AWT with an event delegation model. JDK 1.2 introduced Swing, a richer GUI library that better integrated with native operating system look and feels. Swing components are lightweight compared to heavyweight AWT components. The document also covers GUI component classes, layout managers, menus, labels and event handling in Java GUI programming.
The document outlines the requirements and topics to be covered in an Android training, including developing layouts using XML and Java, running and debugging Android applications, using intents and bundles to pass data between activities, and handling basic data storage using SQLite and memory management. It also provides references and questions for trainees to refer to for more information on Android development concepts and best practices.
Presentation from #andevcon by Anna Schaller
Peter van der Linden, Android Technology Evangelists from the Developer Platforms and Services team at Motorola Mobility. More info at http://developer.motorola.com
Swift is a new programming language created by Apple as an alternative to Objective-C for iOS development. It is faster, safer, and has a cleaner syntax than Objective-C. To start developing iOS apps in Swift, developers need a Mac computer, Xcode installed, and an Apple Developer account. Key aspects of iOS app development in Swift covered in the document include prototyping apps, using Xcode, optionals and auto layout, implementing protocols like UITableViewDelegate, and using MVC architecture.
In Android, the user interface is built using a hierarchy of View and ViewGroup objects. Views are basic UI elements like buttons and text fields, while ViewGroups serve as containers to hold other views and arrange their layout. The UI hierarchy is defined using XML layout files, which map XML elements to their corresponding View classes. These layout files are loaded and inflated into views at runtime. Views can also be created and added programmatically in code. Views handle drawing, interaction events, and other behaviors to display the UI to the user.
This document discusses basic widgets in Android user interfaces. It describes labels, buttons, edit texts, check boxes, spinners, radio groups, radio buttons, images views and image buttons. Labels are used to display text and are not editable. Buttons allow clicking actions. Edit texts are editable like text boxes. Check boxes represent two-state selections. Spinners display a single child like a drop-down list. Radio groups contain radio buttons where only one can be selected at a time. Images can be displayed using image views and buttons. All widgets extend from views and can set properties for visibility, background, focus and enabled status.
The document provides tips for finding resources in the Eclipse workspace using a visitor. It describes creating a class that implements IResourceProxyVisitor and overriding the visit() method. This method would check each resource proxy for a match to the location string and return the resource if found. This allows recursively searching the workspace to locate a resource based on its path or other identifier.
Android is a software stack that includes an operating system, middleware and key applications for mobile devices. It uses the Java programming language and includes features like application frameworks, SQLite for storage, and support for common media formats. The Android architecture consists of applications, an application framework, libraries and services, the Android runtime and the Linux kernel. Activities are the basic building blocks of Android apps and have a defined lifecycle of states they move through as the user interacts with the app.
Invalidation Routines Pounded Into Your Craniumsakrirosenstrom
The document discusses the Flex invalidation mechanism, which is used by the Flex framework to optimize handling of visual changes to components and layout of containers. It introduces the three key methods - commitProperties(), measure(), and updateDisplayList() - that components override to implement invalidation. Components call invalidate() to flag changes, and the layout manager then calls the validation methods in priority order to synchronize updates efficiently across the display list. Examples are provided to illustrate how invalidation works and improves performance over directly calling update().
The document discusses different types of views and view groups in Android user interface development. It describes layouts like LinearLayout, RelativeLayout and FrameLayout that extend the ViewGroup class. These layouts allow arranging views in different orientations using attributes like layout_width, layout_height, layout_weight etc. The document also talks about defining views and layouts in XML files or programmatically at runtime.
The document discusses several new features and APIs in Android 3.0 (Honeycomb) for tablets, including fragments which allow recomposing UI based on factors like screen size, loaders for asynchronously fetching content, an enhanced action bar for navigation and menus, hardware accelerated graphics, and the new holographic UI design. It also questions what some aspects of Android 3.0 may mean for future phone releases and how to detect "tablet-y" systems.
The document provides an overview of Android app development using Java. It discusses key Android concepts like activities, intents, services, and broadcast receivers. It also covers the Android development tools and toolchain, including the emulator. The document demonstrates concepts like activities, intents, services through sample code. It discusses other topics like threads, preferences, security and performance best practices for Android.
The document discusses Android's windowing system architecture and components. It describes the main components as SurfaceManager, WindowManager, and ActivityManager. SurfaceManager is responsible for compositing surfaces. WindowManager creates and lays out surfaces on behalf of clients and dispatches input events. ActivityManager manages activity lifecycles and stacking. The document also covers handling gestures, animations, custom view architecture, using the hierarchy viewer tool, and event propagation in Android views.
This document discusses creating custom views in Android. It covers default views provided by Android, reasons for creating custom views, the responsibilities of views, and how to create custom views by extending the View class and implementing key methods like onDraw(), onMeasure(), and onLayout(). It also discusses compound views, view lifecycles, defining custom attributes, and using custom views in layout files.
The document discusses several design patterns including Iterator, Observer, Strategy, Composite, and Decorator. It provides examples of each pattern and explains the key ideas and benefits of using design patterns, such as allowing reusable and flexible designs that can be communicated through a common vocabulary.
The document discusses several design patterns including Iterator, Observer, Strategy, Composite, and Decorator. It provides examples of each pattern and explains the key ideas and benefits of using design patterns, such as creating reusable and flexible designs that can be communicated effectively.
Presentation about Android custom views held on 05.04.2018 on Infinum Android Talks
Code: https://github.com/MatejVukosav/ConceptView
Event:
https://www.facebook.com/events/626682637663384/
https://infinum.co/our-stuff/android-talks/29
Android App Development - 04 Views and layoutsDiego Grancini
The document discusses views and layouts in Android. It covers the View and ViewGroup classes used to create graphical interfaces. Layouts can be defined in XML files and include common layouts like LinearLayout, RelativeLayout, and ScrollView. It also discusses how to create custom views by extending the View class and implementing common callback methods like onDraw(), onMeasure(), and event handlers. Optimizing custom views to minimize calls to methods like invalidate() and requestLayout() is also covered.
This document discusses the evolution of graphical user interface (GUI) capabilities in the Java programming language. It describes the Abstract Window Toolkit (AWT) introduced in JDK 1.0, which provided basic cross-platform GUI functionality but had limitations. JDK 1.1 improved on AWT with an event delegation model. JDK 1.2 introduced Swing, a richer GUI library that better integrated with native operating system look and feels. Swing components are lightweight compared to heavyweight AWT components. The document also covers GUI component classes, layout managers, menus, labels and event handling in Java GUI programming.
The document outlines the requirements and topics to be covered in an Android training, including developing layouts using XML and Java, running and debugging Android applications, using intents and bundles to pass data between activities, and handling basic data storage using SQLite and memory management. It also provides references and questions for trainees to refer to for more information on Android development concepts and best practices.
Presentation from #andevcon by Anna Schaller
Peter van der Linden, Android Technology Evangelists from the Developer Platforms and Services team at Motorola Mobility. More info at http://developer.motorola.com
Swift is a new programming language created by Apple as an alternative to Objective-C for iOS development. It is faster, safer, and has a cleaner syntax than Objective-C. To start developing iOS apps in Swift, developers need a Mac computer, Xcode installed, and an Apple Developer account. Key aspects of iOS app development in Swift covered in the document include prototyping apps, using Xcode, optionals and auto layout, implementing protocols like UITableViewDelegate, and using MVC architecture.
In Android, the user interface is built using a hierarchy of View and ViewGroup objects. Views are basic UI elements like buttons and text fields, while ViewGroups serve as containers to hold other views and arrange their layout. The UI hierarchy is defined using XML layout files, which map XML elements to their corresponding View classes. These layout files are loaded and inflated into views at runtime. Views can also be created and added programmatically in code. Views handle drawing, interaction events, and other behaviors to display the UI to the user.
This document discusses basic widgets in Android user interfaces. It describes labels, buttons, edit texts, check boxes, spinners, radio groups, radio buttons, images views and image buttons. Labels are used to display text and are not editable. Buttons allow clicking actions. Edit texts are editable like text boxes. Check boxes represent two-state selections. Spinners display a single child like a drop-down list. Radio groups contain radio buttons where only one can be selected at a time. Images can be displayed using image views and buttons. All widgets extend from views and can set properties for visibility, background, focus and enabled status.
The document provides tips for finding resources in the Eclipse workspace using a visitor. It describes creating a class that implements IResourceProxyVisitor and overriding the visit() method. This method would check each resource proxy for a match to the location string and return the resource if found. This allows recursively searching the workspace to locate a resource based on its path or other identifier.
Android is a software stack that includes an operating system, middleware and key applications for mobile devices. It uses the Java programming language and includes features like application frameworks, SQLite for storage, and support for common media formats. The Android architecture consists of applications, an application framework, libraries and services, the Android runtime and the Linux kernel. Activities are the basic building blocks of Android apps and have a defined lifecycle of states they move through as the user interacts with the app.
Invalidation Routines Pounded Into Your Craniumsakrirosenstrom
The document discusses the Flex invalidation mechanism, which is used by the Flex framework to optimize handling of visual changes to components and layout of containers. It introduces the three key methods - commitProperties(), measure(), and updateDisplayList() - that components override to implement invalidation. Components call invalidate() to flag changes, and the layout manager then calls the validation methods in priority order to synchronize updates efficiently across the display list. Examples are provided to illustrate how invalidation works and improves performance over directly calling update().
The document discusses different types of views and view groups in Android user interface development. It describes layouts like LinearLayout, RelativeLayout and FrameLayout that extend the ViewGroup class. These layouts allow arranging views in different orientations using attributes like layout_width, layout_height, layout_weight etc. The document also talks about defining views and layouts in XML files or programmatically at runtime.
The document discusses several new features and APIs in Android 3.0 (Honeycomb) for tablets, including fragments which allow recomposing UI based on factors like screen size, loaders for asynchronously fetching content, an enhanced action bar for navigation and menus, hardware accelerated graphics, and the new holographic UI design. It also questions what some aspects of Android 3.0 may mean for future phone releases and how to detect "tablet-y" systems.
The document provides an overview of Android app development using Java. It discusses key Android concepts like activities, intents, services, and broadcast receivers. It also covers the Android development tools and toolchain, including the emulator. The document demonstrates concepts like activities, intents, services through sample code. It discusses other topics like threads, preferences, security and performance best practices for Android.
3. 1.1 Introduction
Android offers a robust componentized model for building your UI.
It is based on the fundamental layout classes:
View
ViewGroup
The platform includes a variety of prebuiltView andViewGroup subclasses.They are:
Widgets
Layouts
4. 1.1 Introduction (Contd.)
A partial list of available widgets are:
Button
TextView
EditText
ListView
CheckBox
RadioButton
Gallery
Spinner
The more special-purpose widgets are:
AutoCompleteTextView
ImageSwitcher
TextSwitcher
5. 1.2 Why Custom Components? (Not default!)
If none of the prebuilt widgets or layouts meets your needs, you can create your own
View subclass.
This approach above gives you the full control over your widgets.
If you only need to make small adjustments to an existing widget or layout, you can
simply subclass the widget or layout and override its methods.
This approach above concerns with minor changes suitable with your requirements.Thus
it is often easier.
6. 1.3 Some Application Scenarios
You could create a completely custom-renderedView type, for example a "volume
control" knob rendered using 2D graphics, and which resembles an analog electronic
control.
You could combine a group ofView components into a new single component, perhaps
to make something like a ComboBox (a combination of popup list and free entry text
field), a dual-pane selector control (a left and right pane with a list in each where you
can re-assign which item is in which list), and so on.
You could override the way that an EditText component is rendered on the screen with
some special features. Such as having lines like notepad.
You could capture other events like key presses and handle them in some custom way
(such as for a game).
7. 1.4 The Basic Approach
Extend an existing View class or subclass with your own class.
Override some of the methods from the superclass.The superclass methods to override
start with 'on', for example, onDraw(), onMeasure(), and onKeyDown().This is similar
to the 'on…' events in Activity or ListActivity that you override for lifecycle and
other functionality hooks.
Use your new extension class. Once completed, your new extension class can be used in
place of the view upon which it was based.
8. Important Tips !
Extension classes can be defined as inner classes inside the
activities that use them.This is useful because it controls access
to them but isn't necessary (perhaps you want to create a
new publicView for wider use in your application).
9. 1.5 Fully Customized Components
Fully customized components can be used to create graphical components that appear
however you wish.
To create a fully customized component:
The most generic view you can extend View, so you will usually start by extending this to
create your new super component.
You can supply a constructor which can take attributes and parameters from the XML, and you
can also consume your own such attributes and parameters (perhaps the color and range of the
VU meter, or the width and damping of the needle, etc.)
You will probably want to create your own event listeners, property accessors and
modifiers, and possibly more sophisticated behavior in your component class as well.
You will almost certainly want to override onMeasure() and are also likely to need to
override onDraw() if you want the component to show something.While both have default
behavior, the default onDraw() will do nothing, and the default onMeasure() will always set a
size of 100x100 — which is probably not what you want.
Other on... methods may also be overridden as required.
10. 1.5.1 Extend onDraw() and onMeasure()
The onDraw() method delivers you a Canvas upon which you can implement anything
you want: 2D graphics, other standard or custom components, styled text, or anything
else you can think of.
This does not apply to 3D graphics. If you want to use 3D graphics, you must
extend SurfaceView instead ofView, and draw from a separate thread. (An
important fact!)
11. 1.5.1 Extend onDraw() and onMeasure() (Contd.)
onMeasure() should be overridden to efficiently and accurately report the
measurements of its contained parts.
This is made slightly more complex by the requirements of limits from the parent
(which are passed in to the onMeasure() method) and by the requirement to call the
setMeasuredDimension() method with the measured width and height once they have
been calculated.
If you fail to call this method from an overridden onMeasure() method, the result will
be an exception at measurement time.
The detail of onMeasure() method is given in the next slide.
12. 1.5.1 Extend onDraw() and onMeasure() (Contd.)
The overridden onMeasure() method is called with width and height measure
specifications (widthMeasureSpec and heightMeasureSpec parameters, both are
integer codes representing dimensions) which should be treated as requirements for the
restrictions on the width and height measurements you should produce.
Your component's onMeasure() method should calculate a measurement width and
height which will be required to render the component. It should try to stay within the
specifications passed in, although it can choose to exceed them (in this case, the parent
can choose what to do, including clipping, scrolling, throwing an exception, or asking
the onMeasure() to try again, perhaps with different measurement specifications).
Once the width and height are calculated, the setMeasuredDimension(int width, int
height) method must be called with the calculated measurements. Failure to do this will
result in an exception being thrown.
13. 1.6 Framework Summary
Category Methods Description
Creation Constructors There is a form of the constructor
that are called when the view is
created from code and a form that is
called when the view is inflated from
a layout file.The second form should
parse and apply any attributes
defined in the layout file.
onFinishInflate() Called after a view and all of its
children has been inflated from
XML.
Layout onMeasure(int, int) Called to determine the size
requirements for this view and all of
its children.
onLayout(boolean,int, int, int, int) Called when this view should assign
a size and position to all of its
children.
onSizeChanged(int, int, int, int) Called when the size of this view has
changed.
14. 1.6 Framework Summary (Contd.)
Category Methods Description
Drawing onDraw(Canvas) Called when the view should
render its content.
Event processing onKeyDown(int, KeyEvent) Called when a new key event
occurs.
onKeyUp(int, KeyEvent) Called when a key up event occurs.
onTrackballEvent(MotionEvent) Called when a trackball motion
event occurs.
onTouchEvent(MotionEvent) Called when a touch screen motion
event occurs.
Focus onFocusChanged(boolean, int,
Rect)
Called when the view gains or loses
focus.
onWindowFocusChanged(boolean) Called when the window containing
the view gains or loses focus.
Attaching onAttachedToWindow() Called when the view is attached to
a window.
onDetachedFromWindow() Called when the view is detached
from its window.
onWindowVisibilityChanged(int) Called when the visibility of the
window containing the view has
changed.
15. 1.7 Modifying an Existing View Type
In this section, adding some features in a EditText will be discussed.
To accomplish this, we need to do the things described below.
The Definition
Class Initialization
Overridden Methods
Use the Custom Component
These steps will be described in the following slides.
16. 1.7.1 The Definition
The class is defined with the following line:
public class NumberView extends EditText implements OnClickListener,
OnLongClickListener, OnTouchListener
It extends EditText, which is theView we have chosen to customize in this case.When
we are finished, the new class will be able to substitute for a normal EditText view.
As we going to implement OnClickListener, OnLongClickListener,
OnTouchListener, we will be able to override some existing methods to fulfill our
purposes.
In this example we are going to override onTouch() method.
The main purpose of overriding this method is to provide an custom EditText, in
which when user touches, no default keyboard will pop out.
Another important purpose is to provide a user facility to move cursor position
proper with user’s touch event.
17. 1.7.2 Class Initialization
As always, the super is called first. Furthermore, this is not a default constructor, but a
parameterized one.
The EditText is created with these parameters when it is inflated from an XML layout
file, thus, our constructor needs to both take them and pass them to the superclass
constructor as well.
Our implemented code segment is given below.
public NumberView(Context context,AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
setListeners();
c = context;
}
18. 1.7.2 Class Initialization (Contd.)
public NumberView(Context context,AttributeSet attrs) {
super(context, attrs);
setListeners();
c = context;
}
public NumberView(Context context) {
super(context);
setListeners();
//TODOAuto-generated constructor stub
}
19. 1.7.3 Overridden Methods
Here we are only describing the overriding of onTouch method.
@Override
public boolean onTouch(View v, MotionEvent event) {
Layout layout = getLayout();
float x = event.getX() + getScrollX();
float y = event.getY() + getScrollY();
int line = layout.getLineForVertical((int) y);
int offset = layout.getOffsetForHorizontal( line, x);
setSelection(offset); //moving the cursor position on user touch
hideSoftKey();
return true;
}
20. 1.7.3 Overridden Methods (Contd.)
Here is the implementation of hideSoftKey() method.
private void hideSoftKey() {
InputMethodManager imm = (InputMethodManager)
c.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
21. Question-Answer
Question: What is the difference between returning true and false
in the overridden onTouch() method?
Answer: Return true if the listener has consumed the event, false
otherwise.
To be more specific, Returning true means that other views that also
having a touchlistener will not get this event for handling. If you
return false the event will be passed to parent views for handling.
21
22. 1.7.4 Use the Custom Component
We can add our custom EditText in the layout file that can be found under res/layout
folder.The code segment is given below.
<view
class="com.example.androidcustomview.NumberView"
android:id="@+id/yourGivenID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:scrollbars="vertical"
android:fadingEdge="vertical" />
25. 2.1 Creating a View Class
A well-designed custom view is much like any other well-designed class. It encapsulates a
specific set of functionality with an easy to use interface, it uses CPU and memory
efficiently, and so forth. In addition to being a well-designed class, though, a custom view
should:
Conform toAndroid standards
Provide custom styleable attributes that work withAndroid XML layouts
Send accessibility events
Be compatible with multipleAndroid platforms.
26. 2.1.1 Subclass a View
All of the view classes defined in theAndroid framework extend View
Your custom view can also extend View directly, or you can save time by extending one
of the existing view subclasses, such as Button.
To allow the Android DeveloperTools to interact with your view, you must provide
a constructor that takes a Context and an AttributeSet object as parameters.
This constructor allows the layout editor to create and edit an instance of your view.
class PieChart extendsView {
public PieChart(Context context,AttributeSet attrs) {
super(context, attrs);
}
}
27. 2.1.2 Define Custom Attributes
To add a built-in View to your user interface, you specify it in an XML element and
control its appearance and behavior with element attributes.
Well-written custom views can also be added and styled via XML.
To enable this behavior in your custom view, you must:
Define custom attributes for your view in a <declare-styleable> resource element
Specify values for the attributes in your XML layout
Retrieve attribute values at runtime
Apply the retrieved attribute values to your view
In this section you will be able to learn how to define custom attributes and specify their
values.
28. 2.1.2 Define Custom Attributes (Contd.)
To define custom attributes, add <declare-styleable> resources to your project. It is
customary to put these resources into a res/values/attrs.xml file. Here is an example
of an attrs.xml file:
<resources>
<declare-styleable name="PieChart">
<attr name="showText" format="boolean"/>
<attr name="labelPosition" format="enum">
<enum name="left" value="0"/>
<enum name="right" value="1"/>
</attr>
</declare-styleable>
</resources>
This code declares two custom attributes, showText and labelPosition, that belong to a
styleable entity named PieChart.
The name of the styleable entity is, by convention, the same name as the name of the
class that defines the custom view. (An important fact!)
29. 2.1.2 Define Custom Attributes (Contd.)
Once you define the custom attributes, you can use them in layout XML files just like
built-in attributes.
The only difference is that your custom attributes belong to a different namespace.
Instead of belonging to the http://schemas.android.com/apk/res/android namespace,
they belong to http://schemas.android.com/apk/res/[your package name].
For example, here's how to use the attributes defined for PieChart:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
<com.example.customviews.charting.PieChart
custom:showText="true"
custom:labelPosition="left" />
</LinearLayout>
30. 2.1.3 Apply Custom Attributes
When a view is created from an XML layout, all of the attributes in the XML tag are read
from the resource bundle and passed into the view's constructor as an AttributeSet.
Although it's possible to read values from the AttributeSet directly, doing so has some
disadvantages:
Resource references within attribute values are not resolved
Styles are not applied
Instead, pass the AttributeSet to obtainStyledAttributes().This method passes back
a TypedArray array of values that have already been dereferenced and styled.
TheAndroid resource compiler does a lot of work for you to make
calling obtainStyledAttributes() easier. For each <declare-styleable> resource in the res
directory, the generated R.java defines both an array of attribute ids and a set of
constants that define the index for each attribute in the array.You use the predefined
constants to read the attributes from the TypedArray.
31. 2.1.3 Apply Custom Attributes (Contd.)
Here is how the PieChart class reads its attributes:
public PieChart(Context context,AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.PieChart,0, 0);
try {
mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
}
finally {
a.recycle();
}
}
Note that TypedArray objects are a shared resource and must be recycled after
use.(An important fact!)
32. 2.1.4 Add Properties and Events
Attributes can only be read when the view is initialized.
To provide dynamic behavior, expose a property getter and setter pair for each custom
attribute.
The following snippet shows how PieChart exposes a property called showText:
public boolean isShowText() {
return mShowText;
}
public void setShowText(boolean showText) {
mShowText = showText;
invalidate();
requestLayout();
}
Calling to the methods invalidate() and requestLayout() are crucial to ensure that the view behaves
reliably. (Why? Please see the next slide!)
33. 2.1.4 Add Properties and Events (Contd.)
You have to invalidate the view after any change to its properties that might
change its appearance, so that the system knows that it needs to be redrawn.
Likewise, you need to request a new layout if a property changes that might affect
the size or shape of the view.
Forgetting these method calls can cause hard-to-find bugs.
34. Related Topics
For further read, please visit the following links given below.
Custom Drawing
Source: http://developer.android.com/training/custom-views/custom-drawing.html
Making theView Interactive
Source: http://developer.android.com/training/custom-views/making-interactive.html
Optimizing theView
Source: http://developer.android.com/training/custom-views/optimizing-view.html