Chapter 2
Chapter 2
2.1. Introduction
This unit introduces learner to the subject of development of mobile applications. With the increased
usage of mobile devices across the world, more and more applications are being targeted at them. If
an application that is developed for computers can also run on the mobile devices, then the entire
paradigm of application usage changes as it enables the user to run application from wherever he is.
There were different standards on which the mobile networks are based. One of the popular standards
is GSM. In this unit, we introduce mobile software engineering, mobile software frameworks and
tools and generic user interface development in android. There were a number of environments under
which mobile applications can be developed. Some of the popular environments are native
progressive and hybrid application platform developments.
1
below the fold. These factors play a part in your app’s user engagement. The setup of the platforms
can influence how people respond to your app. Moreover, the platforms are also essential when
thinking of other factors such as monetization, security, and the availability of different types of apps.
2. Audience Research
For your idea to become successful, you must first conduct audience research. Knowing your
audience involves understanding the industry and getting in-depth knowledge about the people that
might take an interest in your apps. It is important because users tend to be diverse. You must track
the demographics of the users of your app. That way, you can identify the age, gender, relevant
businesses, and potential customers you can target. If you want your app to solve a problem, you
should not base your decisions on assumptions. Guessing users’ tastes and preferences lead to
poorly executed app development. You can make an approximation of the gender that is likely to use
your app, but its best if you conduct surveys, look into online communities, and use tools to get to
know your market. Creating different personas also helps you visualize the needs of different users.
It helps you identify which parts of the project you must prioritize and which features to include in
your app.
3. App Idea
Apps don’t come out of thin air. They start as brilliant ideas. Unfortunately, not all ideas become
great and successful once you turn them into an app. Remember that working on an app development
project requires money, effort, and time. Therefore, you must first examine your idea before you can
begin working on it. You must first check if your design is unique. With thousands of apps on both
platforms, you are sure to find one that already has the concept you have in mind. Besides being
unique, your app idea must satisfy a need. There’s no use wasting your resources if no one needs and
wants your concept. Of course, you must also find out if your idea has a lot of competition. It may
be difficult to break through in a saturated market. Most of all, you must be able to differentiate your
idea from what’s already available on the platforms. It must also be able to resolve the weaknesses
of the existing competitive apps.
A Nielsen survey on consumer preference for mobile apps vs. mobile sites found that Indian
consumers prefer apps that personalize their experience. You can improve your app idea when
2
you research your audience as well as your competition. It helps strengthen your app idea and push
you to exhaust your brain juices to generate innovative solutions.
5. UI/UX
User interface (UI) and user experience (UX) are part of what keeps users hooked on an app.
According to the founder and CEO of Apps Discover Technologies, Ashish Bahukhandi shared that
successful apps are those that provide a hassle-free experience aside from serving its purpose. Users
prefer apps that are “handier” compared to those that require too much effort to operate. Navigation
and usability aren’t the only ones that matter to the users. They are also receptive to several UI/UX
factors. For instance, an app with low-res images, slow loading times, broken sign up/ login
functionality and app navigation, and poor connectivity to social profiles are all signs of poor UI/UX.
Unnecessary micro-interactions, lags or unresponsive clickable elements, inappropriate spaces, and
mismatch fonts types and size are some of the factors you should watch out for when developing
your app.
6. Testing
Developing and designing your mobile app idea is only half of the job in your mobile app
development journey. You must also run a few tests to ensure your design runs smoothly. It’s a way
to secure that your mobile app has no exceptions and bugs. If you launch your app without testing it,
you can run into problems that can spark fires that are difficult to put out. There are seven ways to
test your app and check if it doesn’t have bugs. You should see if each of the app’s function. Each
3
time you add a function, you must see if the existing features are still working correctly. You must
also look into the app’s integrations and usability. It’s also important to find out if your app is
compatible with different platforms and devices. Most of all, you should test if the app functions
properly at the user’s end before going live. Avinash Tiwari, Co-founder and Director of pCloudy,
states that developers must know the app development ecosystem. You must stay informed of the
latest updates in OS versions as well as market trends. These practices help you anticipate problems
with latest released apps. You should always check release notes to identify potential issues that can
encourage users to abandon your app.
7. Security
Security must be part of your app development process. Users should not have to think of the threat
of malware when they use your app. Thus, you should leverage the security features of the device’s
OS. You can also keep the user’s information safe through encryption. You should also restrict your
app’s permissions to a minimum. Always prioritize security to ensure your app isn’t vulnerable to
external threats.
8. Monitoring
You still have work to do after you publish your mobile app. You must be hands-on with fixes,
performance improvements, changes, and integrating new features. As a developer, you must track
crashes and look at technical information to help you resolve the problems users encounter. You can
also check into analytics as well as recommendations and reviews by users to see how well the market
responds to your app. The information you get from these platforms is what you need to identify
trouble spots and make room for improvement.
Lifecycle management – Once an app is deployed, developers must test, host, deploy, maintain and
analyze its usage throughout its lifecycle. As a result, it’s important for developers to consider the
long-term capabilities and long-term costs of tools.
Delivery – Apps aren’t done when they go into production. They must be dependable. They must
scale. They will need updating based on evolving requirements and end user feedback. Developers
need to make sure the tool they select will allow for easy upgrades, updates, availability, scalability
and performance.
The main considerations for mobile app design are listed below:
4
· Intended utility of the mobile app
• Consumer engagement with richer user experience
• Productivity through efficient flows
• Driving incremental revenue through user stickiness
• Customer conversion
• User loyalty through targeted and personalized offers
· App Architecture
• Native vs. hybrid vs web based on the requirements
• Middleware requirement for centralized configuration
• Offline vs. online capability for storing data
· App Development Principles
• User experience through richer controls and interactive components
• Compatibility on various devices and platforms
• Performance for each screen and task
• Security for data of Productivity enhancement tools
· Target users
• Consumers for B2C apps
• Business for Business to Business (B2B) apps
• Partners for B2B apps or Employees for Business to Employee (B2E) apps
· Testing
• Device testing
• Performance testing
• Various testing scenarios
5
2.3. FRAMEWORKS AND TOOLS
Mobile application frameworks are a software creation platform that includes tools and software,
compilers, debugging tools, and programming interfaces, among other things. Thus, a developer
creates the application’s source code and the framework and uses various elements to generate the
application for the different mobile devices. It is a library that provides the needed basic structure to
develop mobile apps for a particular industry. In terms of how applications work on a smartphone,
mobile apps may be divided into three categories. These are native apps, web apps, and hybrid apps.
• Native apps: Native apps are designed for specific operating systems such as Android, iOS,
and Windows. Apps make use of device features such as RAM, camera, GPS, and so on.
• Progressive Web apps (PWA): Web apps are software that is kept in a distant location and
distributed via the Web using a browser interface. Emails, online shopping sales, auction sites,
weblogs, instant messaging apps, and other web apps are popular.
• Hybrid apps: Hybrid apps are applications that are launched on a smartphone in the same
way that every other application is done. What sets them apart is that hybrids combine
features from native apps and with components from web apps. Such apps are developed
from a single code base for any platform.
A good User Interface (UI) focuses on making user’s interactions simple and efficient. User would
appreciate a website with intuitive user interface that leads them towards their task in most engaging
way. User Interface (UI) design focuses on thinking of a user, what they might need to do when they
visit website and ensure that the interface has elements that are easy to access and understand. Being
a UI designer, one need to understand the goals, skills, preferences and tendencies of the user
to make a better interface.
The Generic User Interface (Generic UI, GUI) framework allows you to create UI screens using Java
and XML. XML provides a declarative approach to the screen layout and reduces the amount of code
which is required for building the user interface.
In supporting international users of mobile applications, default UI is always mandatory. The default
UI development is a generic UI development concept that we should know before
6
internationalization. Generic UI development is knowing how to use Views, ViewGroups, and
different UI widgets in android.
• LinearLayout: A layout that arranges its children in a single column or a single row. The
direction of the row can be set by calling setOrientation( ).
7
• RelativeLayout: A layout where the positions of the children can be described in relation to
each other or to the parent.
• FrameLayout: It is used to block out an area on the screen to display a single item.
• TableLayout: A layout that arranges its children into rows and columns.
• ConstraintLayout: is a layout which allows you to position and size complex components
in a flexible way.
Linear Layout
Linear layout is a view group that aligns all children in a single direction, vertically or horizontally.
Layout direction is specified by android: orientation=” horizontal” or android: orientation=” vertical”
attribute. LinearLayout horizontal arranges the elements horizontally in the LinearLayout.
LinearLayout vertical arranges the elements vertically in the LinearLayout. Example: In the example below
we have arranged a TextView and a Button vertically.
Relative Layout
RelativeLayout lays out elements based on their relationships with one another, and with the parent
container. This is arguably the most complicated layout and we need several properties to actually
get the layout we want.
Relative to container:
These properties will layout elements relative to the parent container.
• android:layout_alignParentBottom-places the element on the bottom of the container.
• android:layout_alignParentLeft-places the element on the left side of the container.
• android:layout_alignParentRight-places the element on the right side of the container.
• android:layout_alignParentTop-places the element on the top of the container.
• android:layout_centerHorizontal-centers the elements horizontally within its parent
container.
• android:layout_centerInParent- centers the elements both horizontally and vertically
within its parent container.
• android:layout_centerVertical- centers the elements vertically within its parent container..
Relative to other Elements:
These properties allow you to layout elements relative to other elements on screen. The value for
each of these elements is the id of the element you are using to layout the new element.
8
Each element that is used in this way must have an ID defined using android:id=”@_id/xxxxx”
where xxxxx is replaced with the desired id. You use “@id/xxxxx” to reference an element by its id.
One thing to remember is that referencing an element before it has been declared will produce an
error.
• android:layout_above- places an element above the specified element.
• android:layout_below- places an element below the specified element.
• android:layout_toLeftOf- places an element to the left of the specified element.
• android:layout_toRightOf- places an element to the right of the specified element.
Relative with other Elements:
These properties allow you to specify how elements are aligned in relation to other elements.
• android:layout_alignBaseline- aligns baseline of the new element with baseline of the
specified element.
• android:layout_alignBottom- aligns bottom of the new element in with bottom of the
specified element.
• android:layout_alignLeft- aligns left edge of the new element with left edge of the
specified element.
• android:layout_alignRight- aligns right edge of the new element with right edge of the
specified element.
• android:layout_alignTop- places top of the new element in alignment with the top of the
specified element.
Table Layout
TableLayout organizes content into rows and columns. Table layouts in android works, in the same way HTML
table layout work. You will use the <TableRow> element to build a row in the table. Each row has
zero or more cells; each cell can hold one View object. TableLayout containers do not display border
lines for their rows, columns, or cells.
Frame Layout
FrameLayout is designed to display a single item at a time. You can have multiple elements within a
FrameLayout but each element will be positioned based on the top left of the screen. Elements that
overlap will be displayed overlapping.
Gravity specifies where the text appears within its container. If the gravity is not set the text will
appear at the top left of the screen.
9
FrameLayout can become more useful when elements are hidden and displayed programmatically.
You can use the attribute android:visibility in the XML to hide specific elements. You can even call
setVisibility method from the code to accomplish the same thing. The three available visibility values
are visible, invisible (does not display but still takes up space in the layout) and gone (does not
display and does not take space in the layout).
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and there are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
• android:id - This is the ID which uniquely identifies the view.
• android:layout_width - This is the width of the layout.
• android:layout_height -This is the height of the layout
• android:layout_marginTop - This is the extra space on the top side of the layout.
• android:layout_marginBottom- This is the extra space on the bottom side of the layout.
• android:layout_marginLeft- This is the extra space on the left side of the layout.
• android:layout_marginRight- This is the extra space on the right side of the layout.
• android:layout_gravity- This specifies how child Views are positioned.
• android:layout_weight- This specifies how much of the extra space in the layout should be
allocated to the View.
• android:layout_x- This specifies the x-coordinate of the layout.
• android:layout_y- This specifies the y-coordinate of the layout.
• android:paddingLeft- This is the left padding filled for the layout.
• android:paddingRight- This is the right padding filled for the layout.
• android:paddingTop- This is the top padding filled for the layout.
• android:paddingBottom-This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in terms of dp
(Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch),
px ( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one of
these constants to set the width or height −
10
• android:layout_width=fill_parent - tells your view to become as big as its parent view.
Gravity attribute plays important role in positioning the view object and it can take one or more
(separated by '|') of the following constant values.
Top 0x30 Push object to the top of its container, not changing its size.
bottom 0x50 Push object to the bottom of its container, not changing its size.
Left 0x03 Push object to the left of its container, not changing its size.
Right 0x05 Push object to the right of its container, not changing its size.
center_vertical 0x10 Place object in the vertical center of its container, not changing its size.
fill_vertical 0x70 Grow the vertical size of the object if needed so it completely fills its
container.
center_horizont 0x01 Place object in the horizontal center of its container, not changing its size.
al
fill_horizontal 0x07 Grow the horizontal size of the object if needed so it completely fills its
container.
Center 0x11 Place the object in the center of its container in both the vertical and
horizontal axis, not changing its size.
Fill 0x77 Grow the horizontal and vertical size of the object if needed so it
completely fills its container.
clip_vertical 0x80 Additional option that can be set to have the top and/or bottom edges of the
child clipped to its container's bounds. The clip will be based on the vertical
gravity: a top gravity will clip the bottom edge, a bottom gravity will clip
the top edge, and neither will clip both edges.
clip_horizontal 0x08 Additional option that can be set to have the left and/or right edges of the
child clipped to its container's bounds. The clip will be based on the
horizontal gravity: a left gravity will clip the right edge, a right gravity will
clip the left edge, and neither will clip both edges.
Start 0x0080000 Push object to the beginning of its container, not changing its size.
3
11
End 0x0080000 Push object to the end of its container, not changing its size.
5
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within the
tree. The syntax for an ID, inside an XML tag is :
android:id="@+id/my_button"
Following is a brief description of @ and + signs −
• The at-symbol (@) at the beginning of the string indicates that the XML parser should parse
and expand the rest of the ID string and identify it as an ID resource.
• The plus-symbol (+) means that this is a new resource name that must be created and added
to our resources. To create an instance of the view object and capture it from the layout, use
the following −
Android provides various UI controls that allow you to build the graphical user interface for your app. These
are TextView, EditText, AutoCompleteTextView, Button, ImageButton, CheckBox, ToggleButton,
RadioButton, RadioGroup, ProgressBar, Spinner, TimePicker, DatePicker etc
12
2.4.2. Create UI Controls
Buttons
In Android, Button represents a push button. A Push buttons can be clicked, or pressed by the user
to perform an action. There are different types of buttons used in android such as
CompoundButton, ToggleButton, RadioButton.
Button is a subclass of TextView class and compound button is the subclass of Button class. On a
button we can perform different actions or events like click event, pressed event, touch event
etc.
Android buttons are GUI components which are sensible to taps (clicks) by the user. When the user
taps/clicks on button in an Android app, the app can respond to the click/tap. These buttons can be
divided into two categories: the first is Buttons with text on, and second is buttons with an image on.
A button with images on can contain both an image and a text. Android buttons with images on are
also called ImageButton.
Example: the following example shows how to create a button via a layout xml file.
<Button
android:id="@+id/btn1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display"
android:onClick="btnClick()"
/>
• android:id- provides a unique identification to a UI element. Thus when there are two or more
buttons, it is this id which helps us to distinguish between the two in java code (usually done
by findViewByID( ) method)
• android:layout_width & android:layout_height- defines the size that the UI element should
occupay.
• android:text- defines the text which the UI element should display. If you want to create an
image button use android:drawableLeft property and set its value
“@mipmap/ic_launcher”. (Where mimap is the directory in which the image is stored and
ic_launcher is name of the image.
Example: the following example shows how to create a button programmatically in java file.
import [Link]
import [Link]
import [Link]
import [Link]
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
13
setContentView([Link].activity_main)
val button = Button(this).apply {
text = "Display"
}
val relativeLayout = findViewById<RelativeLayout>([Link])
[Link](button)
}
}
• Create the instance of the Button class by passing the current context as this.
• Set the text which the button should display.
• Create the object of the ViewGroup (Layout) in which the button needs to be placed
• Find the layout by using findViewById( ) method
• Add the button to the layout by addView function
ImageButton
As the name says, the ImageButton component is a button with an image on it. The ImageButton is
represented by the Android class [Link]. It is similar with the button
component except that its value is an Image than a text.
Example:
• if you want to create an image button use android:src attribute to define the location and
name of the image which you want to use as button.
<ImageButton
...
android:src="@drawable/the_image_button_icon"
/>
• If you want to create the button programmatically add
[Link]([Link].the_image_button_icon); to define the location and name of
the image which you want to use as button.
import [Link]
import [Link]
import [Link]
import [Link]
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
val button = Button(this).apply {
text = "Display"
setBackgroundResource([Link].the_image_button_icon) // Use this to se
t an image as background
}
val relativeLayout = findViewById<RelativeLayout>([Link])
[Link](button)
} }
14
Button Click Event
When the user clicks on a button, the Button object receives an on-click event. To define the click
event handler for a button, add the android:onClick attribute to the <Button> element in your xml
layout. The value for this attribute must be the name of the method you want to call in response to a
click event. For instance android:onClick=”btnOnclick()”. The Activity hosting the layout must then
implement the corresponding method. Example: the following method will display “Button clicked!”
message when a user clicks on the button.
Android Toast
Toast is a notification message that pop up for a specific duration. It only fills the amount of space
required for the message and the current activity remains visible and interactive. The
[Link] class is the subclass of [Link] class.
Constants of Toast Class:
• LENGTH_LONG- displays view for a long duration of time i.e. 3.5 seconds.
(Toast.LENGTH_LONG)
• LENGTH_SHORT- displays view for a short duration of time i.e. 2 seconds.
(Toast.LENGTH_SHORT)
Example:
15
Positioning the Toast:
A standard toast notification appears near the bottom of the screen, centered horizontally. You can
change this position with the setGravity(int, int, int) method.
The method accepts three parameters:
• a gravity constant, an x-position offset and y-position offset.
Example: this example displays the toast at the top-left corner of your application
Android TextView
The TextView view is used to display text to the user. This is the most basic view and one that you
will frequently use when you develop Android applications. If you need to allow users to edit the text
displayed, you should use the subclass of TextView, EditText. In some other platforms the TextView
is commonly known as label view. It’s sole purpose to display a text on the screen. For example: the
following example will display the text “Hello World” on the screen
<TextView
android:id="@+id/txtview "
android:layout_width="fill_parent "
android:layout_height="wrap_content"
android:text="Hello World"
/>
Attributes of TextView:
Some of the attributes of a TextView are:
• id: id is an attribute used to uniquely identify a text view.
• gravity: The gravity attribute is an optional attribute which is used to control the alignment
of the text like left, right, center, top, bottom, center_vertical, center_horizontal etc.
• text: text attribute is used to set the text in a text view. We can set the text in xml as well as
in the kotlin class.
• textColor: textColor attribute is used to set the text color of a text view. Color value is in
the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
• textSize: textSize attribute is used to set the size of text of a text view. We can set the text
size in sp(scale independent pixel) or dp(density pixel).
16
• textStyle: textStyle attribute is used to set the text style of a text view. The possible text styles
are bold, italic and normal. If we need to use two or more styles for a text view then “|”
operator is used for that. Example: android:textStyle=”bold|italics”
• background: background attribute is used to set the background of a text view. We can set
a color or a drawable in the background of a text view.
• padding: padding attribute is used to set the padding from left, right, top or bottom. In above
example code of background we also set the 10dp padding from all the side’s of text view.
Example: Below is the example of TextView in which we display a text view and set the text in
xml file and then change the text on button click event programmatically. Below is the final output
and code:
activity_main.xml [Link]
<?xml version="1.0" encoding="utf-8"?> import [Link]
<RelativeLayout . . .> import [Link]
<TextView import [Link]
android:id="@+id/simpleTextView" import [Link]
android:layout_width="wrap_content" import [Link]
android:layout_height="wrap_content" import [Link]
android:layout_centerHorizontal="true" class MainActivity : AppCompatActivity()
android:text="Before Clicking" {
android:textColor="#f00" override fun
android:textSize="25sp" onCreate(savedInstanceState: Bundle?){
android:textStyle="bold|italic" [Link](savedInstanceState)
android:layout_marginTop="50dp"/> setContentView([Link].activity_main)
<Button val simpleTextView: TextView =
android:id="@+id/btnChangeText" findViewById([Link])
android:layout_width="wrap_content" val changeText: Button =
android:layout_height="wrap_content" findViewById([Link])
android:layout_centerInParent="true" [Link] {
android:background="#f00" [Link] = "After
android:padding="10dp" Clicking"
android:text="Change Text" }
android:textColor="#fff" }}
android:textStyle="bold" />
</RelativeLayout>
Android EditText
EditText view is a subclass of the TextView that allows users to edit its text content. It is also known
as a text field in other platforms. It can be either single line or multi-line. Touching a text field places
the cursor and automatically displays the keyboard. In addition to typing, text fields allow for a
variety of activities such as text selection (cut, copy, paste) and data look-up via auto- completion.
You can specify the type of keyboard you want for your EditText object with the android:inputType
17
attribute. For example, if you want the user to input a phone number, you should use the phone input
type.
Example:
<EditText
android:id="@+id/search "
android:layout_width="fill_parent "
android:layout_height="wrap_content"
android:hint="Search Tex"
android:inputTYpe="text"
android:imeOptions="actionSend"
/>
There are different input types, the most common are:
• text- displays a normal text keyboard
• textEmailAddress- displays a normal text keyboard with the @ character
• textUri- displays a normal text keyboard with the / character
• number- displays a basic number keypad
• phone- displays a phone style keypad
The android:inputType property also allows you to specify certain keyboard behaviors such as
whether to capitalize all new words or use features like auto-complete and spelling suggestions.
• textCapSentences-displays normal text keyboard that capitalizes the first letter for each new
sentence.
• textCapWords- displays normal text keyboard that capitalizes every word.
• textAutoCorrect- displays normal text keyboard that corrects commonly misspelled words
• textPassword- displays normal text keyboard but the characters entered turn into dots.
• textMultiLine- displays normal text keyboard that allow users to input long strings of text
that include line breaks.(carriage return)
18
action by setting the android:imeOptions attribute. For example,
android:imeOptions=”actionSend” in the above example specifies a send action.
Listening to Keyboard Actions
If you have specified a keyboard action for the input method using android:imeOptions attribute,
you can listen for the specific action event using an [Link].
The [Link] interface provides a callback method called
onEditorAction() that indicates the action type invoked with an action ID such as
IME_ACTION_SEND or IME_ACTION_SEARCH. For example, here is how you can listen when
the user clicks the send button on the keyboard.
Attributes of EditText:
EditText supports the attributes mentioned for TextView , the attribute described below and a lot
more:
• hint: hint is an attribute used to set the hint i.e. what you want user to enter in this edit text.
Whenever user start to type in edit text the hint will automatically disappear.
Example: Below is the example of edit text in which we get the value from multiple edittexts and
on button click event the Toast will show the data defined in Edittext.
activity_main.xml [Link]
<?xml version="1.0" encoding="utf-8"?> import
<RelativeLayout ...> [Link]
<EditText import [Link]
android:id="@+id/editText1" import [Link]
android:layout_width="wrap_content" import [Link]
android:layout_height="wrap_content" import [Link]
android:layout_alignParentLeft="true" import [Link]
android:layout_alignParentStart="true" class MainActivity : AppCompatActivity()
android:layout_alignParentTop="true" {
android:layout_marginLeft="50dp" private lateinit var submit: Button
android:layout_marginStart="50dp" private lateinit var name: EditText
android:layout_marginTop="24dp" private lateinit var password: EditText
android:ems="10" private lateinit var email: EditText
android:hint="@string/name" private lateinit var contact: EditText
19
android:inputType="textPersonName" private lateinit var date: EditText
android:selectAllOnFocus="true" />
override fun
<EditText onCreate(savedInstanceState: Bundle?) {
android:id="@+id/editText2"
android:layout_width="wrap_content" [Link](savedInstanceState)
android:layout_height="wrap_content" setContentView([Link].activity_main)
android:layout_alignLeft="@+id/editText1" name = findViewById([Link].editText1)
android:layout_alignStart="@+id/editText1" password = findViewById([Link].editText2)
android:layout_below="@+id/editText1" email = findViewById([Link].editText3)
android:layout_marginTop="19dp" date = findViewById([Link].editText4)
android:ems="10" contact = findViewById([Link].editText5)
android:hint="@string/password_0_9" submit = findViewById([Link])
android:inputType="numberPassword" />
<EditText [Link] {
android:id="@+id/editText3" if ([Link]() ||
android:layout_width="wrap_content" [Link]() ||
android:layout_height="wrap_content" [Link]() ||
android:layout_alignLeft="@+id/editText2" [Link]() ||
android:layout_alignStart="@+id/editText2" [Link]()) {
android:layout_below="@+id/editText2"
android:layout_marginTop="12dp" [Link](applicationContext,
android:ems="10" "Enter the Data",
android:hint="@string/e_mail" Toast.LENGTH_SHORT).show()
android:inputType="textEmailAddress" /> } else {
<EditText
android:id="@+id/editText4" [Link](applicationContext,
android:layout_width="wrap_content" "Name -
android:layout_height="wrap_content" ${[Link]}\n" +
android:layout_alignLeft="@+id/editText3" "Password -
android:layout_alignStart="@+id/editText3" ${[Link]}\n" +
android:layout_below="@+id/editText3" "E-Mail -
android:layout_marginTop="18dp" ${[Link]}\n" +
android:ems="10" "Date -
android:hint="@string/date" ${[Link]}\n" +
android:inputType="date" /> "Contact -
<EditText ${[Link]}",
android:id="@+id/editText5"
android:layout_width="wrap_content" Toast.LENGTH_SHORT).show()
android:layout_height="wrap_content" }
android:layout_alignLeft="@+id/editText4" }
android:layout_alignStart="@+id/editText4" }
android:layout_below="@+id/editText4" }
android:layout_marginTop="18dp"
android:ems="10"
android:hint="@string/contact_number"
android:inputType="phone" />
<Button
android:id="@+id/button"
style="@android:style/[Link]"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/editText5"
20
android:layout_marginTop="62dp"
android:text="@string/submit"
android:textSize="16sp"
android:textStyle="normal|bold" />
</RelativeLayout>
AutoCompleteTextView
An AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of
completion suggestions automatically while the user is typing. The list of suggestions is displayed in
drop down menu. The user can choose an item from there to replace the content of edit box with. It
is the subclass of EditText class.
The list of suggestions is obtained from data adapter and appears only after a given number of
characters defined by threshold.
Steps of creating AutoCompleteTextView
1. Create AutoCompleteTextView in the xml
<AutoCompleteTextView
android:layout_width="match_parent "
android:layout_height="wrap_content"
android:id="@+id/course_list"
/>
21
AutoCompleteTextView Attributes
22
CheckBox
In Android, CheckBox is a type of two state button either unchecked or checked in Android. Or you
can say it is a type of on/off switch that can be toggled by the users. You should use
checkbox when presenting a group of selectable options to users that are not mutually
exclusive. CompoundButton is the parent class of CheckBoxclass.
CheckBox code in XML:
<CheckBox
android:id="@+id/simpleCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple CheckBox"/>
You can check the current state of a check box programmatically by using isChecked() method. This
method returns a Boolean value either true or false, if a check box is checked then it returns true
otherwise it returns false. Below is an example code in which we checked the current state of a check
box.
CheckBox Attributes:
In addition to the above mentioned attributes CheckBox has the following attributes:
• android:autoText- If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
• android:drawableBottom - is the drawable to be drawn below the text.
• android:drawableRight- is the drawable to be drawn to the right of the text.
• android:editable-If set, specifies that this TextView has an input method.
• android:text- is the Text to display.
• android:background- is a drawable to use as the background.
• android:contentDescription- defines text that briefly describes content of the view.
• android:id- supplies an identifier name for this view,
• android:onClick- is the name of the method in this View's context to invoke when the view
is clicked.
• android:visibility- controls the initial visibility of the view.
Example: Below is the example of CheckBox in Android, in which we display five check boxes
using background and other attributes we discusses earlier in this post. Every check box represents a
23
different subject name and whenever you click on a check box then text of that checked check box is
displayed in a toast.
activity_main.xml [Link]
<?xml version="1.0" encoding="utf-8"?> import [Link]
<RelativeLayout ...> import [Link]
<TextView import [Link]
import [Link]
android:layout_width="wrap_content" import
android:layout_height="wrap_content" [Link]
android:text="Select Your Programming import [Link]
language: "
android:textColor="#f00" class MainActivity : AppCompatActivity(),
android:textSize="20sp" [Link] {
android:textStyle="bold" /> private lateinit var androidCheckBox:
<LinearLayout CheckBox
android:id="@+id/linearLayout" private lateinit var javaCheckBox: CheckBox
android:layout_width="fill_parent" private lateinit var phpCheckBox: CheckBox
android:layout_height="wrap_content"
android:layout_marginTop="30dp" override fun onCreate(savedInstanceState:
android:background="#e0e0e0" Bundle?) {
android:orientation="vertical"> [Link](savedInstanceState)
<CheckBox
android:id="@+id/androidCheckBox" setContentView([Link].activity_main)
android:layout_width="wrap_content"
android:layout_height="wrap_content" androidCheckBox =
android:layout_centerHorizontal="true" findViewById([Link])
android:checked="false"
android:padding="20dp" [Link](this)
android:text="@string/android"
android:textColor="#44f" javaCheckBox =
android:textSize="20sp" findViewById([Link])
android:textStyle="bold|italic" /> [Link](this)
<CheckBox phpCheckBox = findViewById([Link])
android:id="@+id/javaCheckBox" [Link](this)
android:layout_width="wrap_content" }
android:layout_height="wrap_content" override fun onClick(view: View) {
android:layout_centerHorizontal="true" when ([Link]) {
android:checked="false" [Link] -> {
android:padding="20dp" if ([Link]) {
android:text="@string/java" [Link](applicationContext, "Android",
android:textColor="#f44" Toast.LENGTH_LONG).show()
android:textSize="20sp" }
android:textStyle="bold|italic" /> }
<CheckBox [Link] -> {
android:id="@+id/phpCheckBox" if ([Link]) {
android:layout_width="wrap_content" [Link](applicationContext, "Java",
android:layout_height="wrap_content" Toast.LENGTH_LONG).show()
android:layout_centerHorizontal="true" }
24
}
if ([Link]) {
android:checked="false" [Link](applicationContext,
android:textColor="#444" "PHP",
android:text="@string/php" Toast.LENGTH_LONG).show()
android:textSize="20sp" }
android:textStyle="bold|italic" /> } } }}
</LinearLayout>
[Link]
</RelativeLayout>
<resources>
<string name="app_name">CheckBoxExample</string>
<string name="hello_world">Hello world! </string>
<string name="action_settings">Settings</ string>
<string name="android">Android</string>
<string name="java">Java</string>
<string name="php">PHP</string>
</resources>
ToggleButton
ToggleButton allow the users to change the setting between two states like turn on/off your wifi,
Bluetooth etc from your phone’s setting menu. Since, Android 4.0 version ( API level 14 ) there is
an another kind of ToggleButton called Switch which provide the user slider control. You can learn
more about it reading Switch tutorial. Android Switch and ToggleButton both are the subclasses
of compoundButton class.
ToggleButton code in XML:
<ToggleButton
android:id="@+id/simpleToggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
ToggleButton Attributes
In addition to the above mentioned attributes ToggleButton has the following attributes:
• android:disabledAlpha - is the alpha to apply to the indicator when disabled.
• android:textOff - is the text for the button when it is not checked.
• android:textOn - is the text for the button when it is checked.
• android:autoText - If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
• android:drawableBottom - is the drawable to be drawn below the text.
• android:drawableRight - is the drawable to be drawn to the right of the text
• android:editable-If set, specifies that this TextView has an input method.
• android:text - is the Text to display. Inherited from [Link] Class:
• android:background - is a drawable to use as the background.
• android:contentDescription - defines text that briefly describes content of the view.
• android:id - is supplies an identifier name for this view,
• android:onClick- is the name of the method in this View's context to invoke when the view
is clicked.
• android:visibility - controls the initial visibility of the view.
• android:checked: checked is an attribute of toggle button used to set the current state of a
toggle button. The value should be true or false where true shows the checked state and false
shows unchecked state of a toggle button.
• android:drawableBottom, drawableTop, drawableRight And drawableLeft: These
attribute draw the drawable below, top, right and left of the text of ToggleButton
Example: Below is the example of ToggleButton in Android Studio. In this example we display two
toggle button with background and one “submit” button using attributes discussed earlier in this post.
Whenever user click on the submit button, the current state of both toggle button’s is displayed in a
Toast.
activity_main.xml [Link]
<?xml version="1.0" encoding="utf-8"?> import [Link]
<LinearLayout . . . > import [Link]
<LinearLayout import [Link]
android:layout_width="wrap_content" import [Link]
android:layout_height="wrap_content" import [Link]
26
android:layout_gravity="center_horizontal" import [Link]
android:orientation="horizontal"> tActivity
<ToggleButton
android:id="@+id/simpleToggleButton1" class MainActivity : AppCompatActivity
android:layout_width="wrap_content" () {
RadioButton
In Android, RadioButton are mainly used together in a RadioGroup. In RadioGroup checking the
one radio button out of several radio button added in it will automatically unchecked all the others. It
means at one time we can checked only one radio button from a group of radio buttons which belong
to same radio group. The most common use of radio button is in Quiz Android App code. RadioButon
is a two state button that can be checked or unchecked. If a radio button is unchecked then a user can
check it by simply clicking on it. Once a RadiaButton is checked by user it can’t be unchecked by
simply pressing on the same button. It will automatically unchecked when you press any other
RadioButton within same RadioGroup.
27
RadioGroup is a widget used in Android for the grouping of radio buttons and provide the feature of
selecting only one radio button from the set. When a user try to select any other radio button within
same radio group the previously selected radio button will be automatically unchecked.
RadioGroup And RadioButton code in XML:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/simpleRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/simpleRadioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
RadioButton Attributes: RadioButton supports the attributes mentioned for most UI widgets.
Example: Below is the example of Radiobutton in Android where we display true and false radio
buttons with background and other attributes. The radio buttons are used to select your answer for
the given question with one “submit” button.
28
activity_main.xml [Link]
<?xml version="1.0" encoding="utf-8"?> import [Link]
<LinearLayout . . . > import [Link]
<LinearLayout import [Link]
android:layout_width="fill_parent" import [Link]
android:layout_height="wrap_content" import [Link]
android:background="#e0e0e0" import
android:orientation="vertical"> [Link]
<TextView
android:layout_width="wrap_content" class MainActivity : AppCompatActivity() {
29
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Android - Event Handling
Events are a useful way to collect data about a user's interaction with interactive components of
Applications. Like button presses or screen touch etc. The Android framework maintains an event
queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take
appropriate action as per requirements.
There are three concepts related to Android Event Management −
• Event Listeners − An event listener is an interface in the View class that contains a single
callback method. These methods will be called by the Android framework when the View to
which the listener has been registered is triggered by user interaction with the item in the UI.
• Event Listeners Registration − Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is called when the Event Listener
fires the event.
• Event Handlers − When an event happens and we have registered an event listener for the
event, the event listener calls the Event Handlers, which is the method that actually handles
the event.
Event Listeners & Event Handlers
OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget
onClick()
like button, text, image etc. You will use onClick() event handler to handle such
event.
OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget
onLongClick()
like button, text, image etc. for one or more seconds. You will use
onLongClick() event handler to handle such event.
OnFocusChangeListener()
onFocusChange() This is called when the widget looses its focus ie. user goes away from the
view item. You will use onFocusChange() event handler to handle such event.
OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a
onKey() hardware key on the device. You will use onKey() event handler to handle such
event.
30
OnTouchListener()
This is called when the user presses the key, releases the key, or any movement
onTouch()
gesture on the screen. You will use onTouch() event handler to handle such
event.
OnMenuItemClickListener()
onMenuItemClick() This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.
onCreateContextMenuItemListener()
onCreateContextMenu() This is called when the context menu is being built(as the result of a sustained
"long click)
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So refer the official documentation
for Android application development in for further information.
Event Listeners Registration
Event Registration is the process by which an Event Handler gets registered with an Event Listener
so that the handler is called when the Event Listener fires the event. Though there are several tricky
ways to register your event listener for any event, but some of them are explained below.
• Using an Anonymous Inner Class
• Activity class implements the Listener interface.
• Using Layout file activity_main.xml to specify event handler directly.
Event listeners registration using an anonymous inner class
Here you will create an anonymous implementation of the listener and will be useful if each class is
applied to a single control only and you have advantage to pass arguments to event handler. In this
approach event handler methods can access private data of Activity. No reference is needed to call to
Activity. But if you applied the handler to more than one control, you would have to cut and paste
the code for the handler and if the code for the handler is long, it makes the code harder to maintain.
Steps
1. Create an Android application and name it as EventDemo under a package
[Link] as explained in the Hello World Example chapter.
2. Modify java/[Link] file to add click event listeners and handlers for a button
defined.
3. Modify the default content of res/layout/activity_main.xml file to include Android UI
controls.
31
5. Run the application to launch Android emulator and verify the result of the changes done in
the application.
Following is the content of the modified main activity file
src/[Link]/[Link]. This file can include each of the
fundamental lifecycle methods.
package [Link]
32
Registration using the activity implements listener interface
Here your Activity class implements the Listener interface and you put the handler method in the
main Activity and then you call setOnClickListener(this). This approach is fine if your application
has only a single control of that Listener type otherwise you will have to do further programming to
check which control has generated event. Second you cannot pass arguments to the Listener so, again,
works poorly for multiple controls.
Following are the simple steps to show how we will make use of separate Listener class to register
and capture click event. Similar way you can implement your listener for any other required event
type.
Following are the simple steps to show how we will implement Listener class to register and capture
click event. Similar way you can implement your listener for any other required event type. Steps
1. We do not need to create this application from scratch, so let's make use of above created
Android application EventDemo.
2. Modify java/[Link] file to add click event listeners and handlers for a button
defined.
3. We are not making any change in res/layout/activity_main.xml, it will remain as shown
above.
4. We are also not making any change in res/values/[Link] file, it will also remain as
shown above.
5. Run the application to launch Android emulator and verify the result of the changes done in
the application.
Following is the content of the modified main activity file
src/[Link]/[Link]. This file can include each of the fundamental
lifecycle methods.
package [Link]
33
// Implement the OnClickListener callback
override fun onClick(v: View) {
if ([Link] == [Link].button_s) {
// Find the text view
val txtView: TextView = findViewById([Link].text_id)
// Change text size
[Link] = 14f
}
}
3. Modify layout file res/layout/activity_main.xml, to specify event handlers for the two
buttons.
4. We are also not making any change in res/values/[Link] file, it will also remain as
shown above.
5. Run the application to launch Android emulator and verify the result of the changes done in
the application.
34
Following is the content of the modified main activity file
src/[Link]/[Link]. This file can include each of the fundamental
lifecycle methods.
package [Link]
android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:capitalize="characters"
android:text="@string/hello_world" />
</LinearLayout>
35