Custom Views
Custom Views
Graphics and animation – Custom views, Canvas, Animation APIs, Multimedia – Audio/Video
playback and record, Location awareness.
Native data handling –file I/O, Shared preferences, Mobile databases such as SQLite, and
Enterprise data access (via Internet/Intranet).
1. Custom Views:
Android offers a sophisticated and powerful componentized model for building your UI, based
on the fundamental layout classes: View and ViewGroup. To start with, the platform includes a
variety of prebuilt View and ViewGroup subclasses — called widgets and layouts,
respectively — that you can use to construct your UI.
If none of the prebuilt widgets or layouts meets our needs, we can create our own View
subclass.
Creating your own View subclasses gives you precise control over the appearance and function
of a screen element. Some examples of what we can do with custom views:
You could create a completely custom-rendered View type, for example a "volume
control" knob rendered using 2D graphics.
You could combine a group of View 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.
You could capture other events like key presses and handle them in some custom way
(such as for a game).
View lifecycle
Constructor
Every view starts it’s life from a Constructor.
First, create a new file and call it attrs.xml. In that file could be all the attributes for different
custom views
onAttachedToWindow
After parent view calls addView(View) that view will be attached to a window. At this stage our
view will know the other views that it is surrounded by.
onMeasure
Means that our custom view is on stage to find out it’s own size. It’s very important method, as
for most cases you will need your view to have specific size to fit in your layout.
onLayout
This method, incorporates assigning a size and position to each of its children.
onDraw
That’s where the magic happens. Having both Canvas and Paint objects will allow you draw
anything you need.
A Canvas instance comes as onDraw parameter, it basicly respond for drawing a different
shapes, while Paint object defines that color that shape will get.
View Update
From a view lifecycle diagram you may notices that there are two methods that leads view to
redraw itself. invalidate() and requestLayout() methods will help you to make an interactive
custom view.
2. Canvas
The Canvas class holds the "draw" calls. To draw something, you need 4 basic components:
Create a Canvas member variable mCanvas. The Canvas object stores information on
what to draw onto its associated bitmap. For example, lines, circles, text, and custom
paths.
Create a Paint member variable mPaint and initialize it with default values. The Paint
objects store how to draw.
Create a Bitmap member variable mBitmap.
Create a member variable for the ImageView, mImageView. A view, in this example an
ImageView, is the container for the bitmap.
III. Fix the onCreate method and customize the mPaint member variable
IV. Implement the drawSomething() click handler method: The drawSomething() method
is where all the interaction with the user and drawing on the canvas are implemented.
3. Animation APIs
Animations can add visual cues that notify users about what's going on in your app.
They are especially useful when the UI changes state, such as when new content
loads or new actions become available. Animations also add a polished look to your
app, which gives it a higher quality look and feel.
Animate bitmaps
When you want to animate a bitmap graphic such as an icon or illustration, you should use
the drawable animation APIs. Usually, these animations are defined statically with a
drawable resource, but you can also define the animation behavior at runtime.
For example, animating a play button transforming into a pause button when tapped is a nice
way to communicate to the user that the two actions are related, and that pressing one makes
the other visible.
To move, reveal, or hide views within the current layout, you can use the property
animation system provided by the android.animation package, available in Android
3.0 (API level 11) and higher.
These APIs update the properties of your View objects over a period of time,
continuously redrawing the view as the properties change.
For example, when you change the position properties, the view moves across the
screen, or when you change the alpha property, the view fades in or out.
Physics-based motion
Whenever possible, your animations should apply real-world physics so they are natural-
looking. For example, they should maintain momentum when their target changes, and make
smooth transitions during any changes.
To provide these behaviors, the Android Support library includes physics-based animation
APIs that rely on the laws of physics to control how your animations occur.
Spring Animation
Fling Animation
Playing Audio
In terms of audio playback, most implementations of Android support AAC LC/LTP, HE-
AACv1 (AAC+), HE-AACv2 (enhanced AAC+), AMR-NB, AMR-WB, MP3, MIDI, Ogg
Vorbis, and PCM/WAVE formats.
Audio playback can be performed using either the MediaPlayer or the AudioTrack classes.
AudioTrack is a more advanced option that uses streaming audio buffers and provides greater
control over the audio. The MediaPlayer class, on the other hand, provides an easier
programming interface for implementing audio playback and will meet the needs of most audio
requirements.
The MediaPlayer class has associated with it a range of methods that can be called by an
application to perform certain tasks. A subset of some of the key methods of this class is as
follows:
create() – Called to create a new instance of the class, passing through the Uri of the
audio to be played.
setDataSource() – Sets the source from which the audio is to play.
prepare() – Instructs the player to prepare to begin playback.
start() – Starts the playback.
pause() – Pauses the playback. Playback may be resumed via a call to the resume()
method.
stop() – Stops playback.
setVolume() – Takes two floating-point arguments specifying the playback volume for
the left and right channels.
resume() – Resumes a previously paused playback session.
reset() – Resets the state of the media player instance. Essentially sets the instance back
to the uninitialized state. At a minimum, a reset player will need to have the data source
set again and the prepare() method called.
release() – To be called when the player instance is no longer needed. This method
ensures that any resources held by the player are released.
mediaPlayer.setDataSource("http://www.ebookfrenzy.com/myaudio.mp3");
mediaPlayer.prepare();
mediaPlayer.start();
As with audio playback, recording can be performed using a number of different techniques. One
option is to use the MediaRecorder class, which, as with the MediaPlayer class, provides a
number of methods that are used to record audio:
setAudioSource()' – Specifies the source of the audio to be recorded (typically this will
be MediaRecorder.AudioSource.MIC for the device microphone).
setVideoSource() – Specifies the source of the video to be recorded (for example
MediaRecorder.VideoSource.CAMERA).
setOutputFormat() – Specifies the format into which the recorded audio or video is to
be stored (for example MediaRecorder.OutputFormat.AAC_ADTS).
setAudioEncoder() – Specifies the audio encoder to be used for the recorded audio (for
example MediaRecorder.AudioEncoder.AAC).
setOutputFile() – Configures the path to the file into which the recorded audio or video
is to be stored.
prepare() – Prepares the MediaRecorder instance to begin recording.
start() - Begins the recording process.
stop() – Stops the recording process. Once a recorder has been stopped, it will need to be
completely reconfigured and prepared before being restarted.
reset() – Resets the recorder. The instance will need to be completely reconfigured and
prepared before being restarted.
release() – Should be called when the recorder instance is no longer needed. This method
ensures all resources held by the instance are released.
A typical implementation using this class will set the source, output and encoding format and
output file. Calls will then be made to the prepare() and start() methods. The stop() method will
then be called when recording is to end followed by the reset() method. When the application no
longer needs the recorder instance a call to the release() method is recommended:
MediaRecorder mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setOutputFile(audioFilePath);
mediaRecorder.prepare();
mediaRecorder.start();
.
.
.
mediaRecorder.stop()
mediaRecorder.reset()
mediaRecorder.release()
In order to record audio, the manifest file for the application must include the
android.permission.RECORD_AUDIO permission:
5. Location awareness
With the help of Google Play services, we can add location awareness to our app with automated
location tracking, geofencing, and activity recognition.
The Location object represents a geographic location which can consist of latitude, longitude,
time stamp, and other information such as bearing, altitude and velocity. There are following
important methods which you can use with Location object to get location specific information:
To get the current location, create a location client which is LocationClient object, connect it to
Location Services using connect() method, and then call its getLastLocation() method. This
method returns the most recent location in the form of Location object that contains latitude and
longitude coordinates and other information as explained above. To have location based
functionality in your activity, you will have to implement two interfaces −
GooglePlayServicesClient.ConnectionCallbacks
GooglePlayServicesClient.OnConnectionFailedListener
If you are willing to have location updates, then apart from above mentioned interfaces,
you will need to implement LocationListener interface as well.
Once you have Location object, you can use Geocoder.getFromLocation() method to
get an address for a given latitude and longitude. This method is synchronous, and may
take a long time to do its work, so you should call the method from the
doInBackground() method of an AsyncTask class.
6. File I/O
https://developer.android.com/training/data-storage/files.html#InternalVsExternalStorage
7. Shared preferences
Shared Preferences allows activities and applications to keep preferences, in the form of key-value
pairs similar to a Map that will persist even when the user closes the application.
Android stores Shared Preferences settings as XML file in shared_prefs folder under
DATA/data/{application package} directory. The DATA folder can be obtained by calling
Environment.getDataDirectory().
SharedPreferences is application specific, i.e. the data is lost on performing one of the
following options:
As the name suggests, the primary purpose is to store user-specified configuration details, such
as user specific settings, keeping the user logged into the application.
PREFS_NAME is the name of the file and mode is the operating mode.
MODE_PRIVATE: the default mode, where the created file can only be accessed by the
calling application
MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and
likely to cause security holes in applications
MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and
likely to cause security holes in applications
MODE_MULTI_PROCESS: This method will check for modification of preferences
even if the Shared Preference instance has already been loaded
MODE_APPEND: This will append the new preferences with the already existing
preferences
MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set,
it would enable write ahead logging by default
Initialization
We need an editor to edit and save the changes in shared preferences. The following code can be
used to get the shared preferences.
Storing Data
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't
need to establish any kind of connections for it like JDBC,ODBC e.t.c
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own
databases
Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you
have to receive in your own object.Its syntax is given below
Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
This will insert some values into our table in our database. Another method that also does the
same job but take some additional parameter is given below
Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
For managing all the operations related to the database, an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below