0% found this document useful (0 votes)
25 views

Unit-3 Session 3

The document discusses creating custom views in Android mobile application development. It covers extending existing views, creating compound controls by combining multiple views, and building entirely new views from scratch. It provides examples of overriding methods like onDraw() to customize a view's appearance and handling user interaction events. The document also discusses using custom views within layouts and code, like any other built-in view.

Uploaded by

Rüby Dharshy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Unit-3 Session 3

The document discusses creating custom views in Android mobile application development. It covers extending existing views, creating compound controls by combining multiple views, and building entirely new views from scratch. It provides examples of overriding methods like onDraw() to customize a view's appearance and handling user interaction events. The document also discusses using custom views within layouts and code, like any other built-in view.

Uploaded by

Rüby Dharshy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Mobile Application

Development
CREATING NEW VIEWS

 The ability to extend existing Views, assemble composite controls, and


create unique new Views makes it possible to implement beautiful UIs
optimized for your application’s workflow.
 Android lets you subclass the existing View toolbox or implement your
own View controls, giving you total freedom to tailor your UI to
optimize the user experience.
 Modify or extend the appearance and/or behavior of an existing
View
when it supplies the basic functionality you want. By overriding
the event handlers and/or onDraw, but still calling back to the
superclass’s methods, you can customize a View without having to
re-implement its functionality. For example, you could customize a
TextView to display numbers using a set number of decimal points.

 Combine Views to create atomic, reusable controls that leverage the


functionality of several interconnected Views. For example, you
could create a stopwatch timer by combining a
TextView and a Button that resets the counter when clicked.

 Create an entirely new control when you need a completely


different interface that you can’t get by changing or combining
existing controls.
Modifying Existing Views

 The toolbox includes Views that provide many common UI


requirements, but the controls are necessarily generic.
 By customizing these basic Views you avoid reimplementing existing
behavior while still tailoring the user interface, and functionality, to
your application’s needs.
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView (Context context, AttributeSet attrs, int defStyle)
{ super(context, attrs, defStyle);
}
public MyTextView (Context context)
{ super(context); }
public MyTextView (Context context, AttributeSet attrs)
{ super(context, attrs); } }
 To override the appearance or behavior of your new View, override and
extend the event handlers associated with the behavior you want to
change.
 The onDraw method is overridden to modify the View’s appearance,
and the onKeyDown handler is overridden to allow custom key-press
handling.
Customizing Your To-Do List
1. Create a new TodoListItemView class that extends TextView. Include a stub for

overriding the onDraw method, and implement constructors that call a new init

method stub.

2. Create a new colors.xml resource in the res/values folder. Create new color

values for the paper, margin, line, and text colors.

3. Create a new dimens.xml resource file and add a new value for the paper’s

margin width.

4. With the resources defined, you’re ready to customize the TodoListItemView

appearance. Create new private instance variables to store the Paint objects

you’ll use to draw the paper background and margin. Also create variables for

the paper color and margin width values.


5. To draw the paper, override onDraw and draw the image using the Paint
objects you created. Once you’ve drawn the paper image, call the
superclass’s onDraw method and let it draw the text as usual.
6. That completes the TodoListItemView implementation. To use it in the
To-Do List Activity you need to include it in a new layout and pass that
layout in to the Array Adapter constructor. Start by creating a new
todolist_item.xml resource in the res/layout folder. It will specify how
each of the to-do list items is displayed.
7. Now open the ToDoList Activity class. The final step is to change the
parameters passed in to the ArrayAdapter in onCreate. Replace the
reference to the default android.R.layout.simple_list_item_1 with a
reference to the new R.layout .todolist_item
Creating Compound Controls

 Compound controls are atomic, reusable Views that


contain multiple child controls laid out and wired together.
 When you create a compound control you define the
layout, appearance, and interaction of the Views it
contains.
 It create compound controls by extending a ViewGroup
Creating a compound control

public class MyCompoundView extends LinearLayout


{
public MyCompoundView(Context context)
{
super(context);
}
public MyCompoundView(Context context, AttributeSet attrs) {
super(context, attrs);
}}
A compound View layout resource
Creating Custom Views
 Creating completely new Views gives you the power to fundamentally
shape the way your applications look and feel.
 By creating your own controls you can create user interfaces that are
uniquely suited to your users’ needs.
 To create new controls from a blank canvas you extend either the View
or SurfaceView classes.
 The View class provides a Canvas object with a series of draw methods
and Paint classes.
 To create a visual interface with bitmaps and raster graphics. You can
then override user events like screen touches or key presses to provide
interactivity.
 In situations in which extremely rapid repaints and 3D graphics aren’t
required, the View base class offers a powerful lightweight solution.
 The SurfaceView class provides a Surface object that supports drawing
from a background thread and using openGL for 3D graphics.
 This is an excellent option for graphics-heavy controls that are
frequently updated or that display complex graphical information,
particularly games and 3D visualizations.
Creating a New Visual Interface

 The base View class presents a distinctly empty 100-pixel-by-


100-pixel square.
 To change the size of the control and display a more compelling
visual interface, you need to override the onMeasure and
onDraw methods.
 Within onMeasure the new View will calculate the height and
width it will occupy given a set of boundary conditions. The
onDraw method is where you draw on the Canvas.
Drawing Your Control

 The onDraw method is where the magic happens. If you’re creating a


new widget from scratch, it’s because you want to create a completely
new visual interface.
 The Canvas parameter in the onDraw method is the surface you’ll use to
bring your imagination to life.
 Android provides a variety of tools to help draw your design on the
Canvas using various Paint objects.
 The Canvas class includes helper methods for drawing primitive 2D
objects including circles, lines, rectangles, text, and Drawables (images).
 It also supports transformations that let you rotate, translate (move),
and scale (resize) the Canvas while you draw on it.
 When these tools are used in combination with Drawables and the
Paint class (which offer a variety of customizable fills and pens), the
complexity and detail that your control can render are limited only by
the size of the screen and the power of the processor rendering it.
Sizing Your Control
 Unless you conveniently require a control that always
occupies a space 100 pixels square, you will also need to
override onMeasure.
 The onMeasure method is called when the control’s parent
is laying out its child controls. It passes in two parameters:
 widthMeasureSpec and heightMeasureSpec. They specify
the space available for the control and some metadata
describing that space. Rather than return a result.
 It pass the View’s height and width into the
setMeasuredDimension method.
Handling User Interaction Events

 In order for your new View to be interactive, it will need to respond to user
events like key presses, screen touches, and button clicks.
 Android exposes several virtual event handlers, listed here, that let you
react to user input:
 onKeyDown Called when any device key is pressed; includes the D-pad,
keyboard, hang-up, call, back, and camera buttons
 onKeyUp Called when a user releases a pressed key

 onTrackballEvent Called when the device’s trackball is moved

 onTouchEvent Called when the touch screen is pressed or released, or


when it detects movement
Creating a Compass View Example
 create a new Compass View by extending the View class.
 This View will display a traditional compass rose to indicate a
heading/orientation.
 A compass is an example of a UI control that requires a radically different
visual display from the text Views and Buttons available in the SDK toolbox,
making it an excellent candidate for building from scratch.
Using Custom Controls
 created your own custom Views, you can use them within code and
layouts as you would any other View.
 Note that you must specify the fully qualified class name when you
create a new node in the layout definition.

<com.paad.compass.CompassView
android:id=”@+id/compassView”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
/>
inflate the layout and get a reference to the CompassView, as usual, using the
following code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CompassView cv = (CompassView)this.findViewById(R.id.compassView);
cv.setBearing(45);
}
You can also add your new view to a layout in code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CompassView cv = new CompassView(this);
setContentView(cv);
cv.setBearing(45);
}
INTRODUCING ADAPTERS
 Adapters are used to bind data to View Groups that extend the
AdapterView (such as listView or gallery) class.
 Adapters are responsible for creating child Views that represent
the underlying data within the bound parent View.
Introducing Some Native Adapters

 Android supplies a set of Adapters that can pump data from common data
sources (including arrays and Cursors) into the native controls that extend
Adapter View.
 ArrayAdapter — The Array Adapter uses generics to bind an Adapter View
to an array of objects of the specified class. By default, the Array Adapter uses
the toString value of each object in the array to create and populate Text
Views.
SimpleCursorAdapter — The Simple Cursor Adapter enables you to bind the
Views within a layout to specific columns contained within a Cursor.
Customizing the Array Adapter
 Array Adapter uses the toString values of each item within an object array to
populate a Text View within the layout.
 Array Adapter to populate the layout used for each View to represent the
underlying array data.
 The getView method is used to construct, inflate, and populate the View that will
be added to the parent Adapter View class (e.g., List View), which is being bound
to the underlying array using this Adapter.
 The getView method receives parameters that describe the position of the item
to be displayed, the View being updated (or null), and the View Group into which
this new View will be placed.
 A call to getItem will return the value stored at the specified index in the
underlying array.
 Return the newly created and populated (or updated) View instance as a result
from this method.
Using Adapters to Bind Data to a View

 An Adapter to an AdapterView-derived class, call the View’s


setAdapter method, passing in an Adapter instance.

ArrayList<String> myStringArray = new ArrayList<String>();


int layoutID = android.R.layout.simple_list_item_1;
ArrayAdapter<String> myAdapterInstance;
myAdapterInstance =
new ArrayAdapter<String>(this, layoutID, myStringArray);
myListView.setAdapter(myAdapterInstance);
Customizing the To-Do List Array Adapter

 To-Do List project, storing each item as a ToDoItem object that


includes the date each item was created.
 ArrayAdapter to bind a collection of ToDoItem objects to the
ListView and customize the layout used to display each to-do item
within the List View.
Using the Simple Cursor Adapter

 The SimpleCursorAdapter is used to bind a Cursor to an Adapter View using


a layout to define the UI of each row/item.
 The content of each row’s View is populated using the column values of the
corresponding row in the underlying Cursor.
 Construct a Simple Cursor Adapter by passing in the current context, a layout
resource to use for each item, a Cursor that represents the data to display,
and two integer arrays:
 one that contains the indexes of the columns from which to source the data.

 second (equally sized) array that contains resource IDs to specify which
Views within the layout should be used to display the contents of the
corresponding columns.

You might also like