Android UI Controls Overview
Android UI Controls Overview
Input controls are the interactive components in your app's user interface. Android provides a wide variety of
controls you can use in your UI, such as buttons, text fields, seek bars, check box, zoom buttons, toggle buttons,
and many more.
View
The View class is a superclass for all GUI components in Android. For instance, the TextView class which is used
to display text labels in Android apps is a subclass of View. Android contains the following commonly used View
subclasses:
TextView
EditText
ImageView
ProgressBar
Button
ImageButton
CheckBox
DatePicker
These are only some of the many, many subclasses of the View class.
ViewGroup
The ViewGroup class is a subclass of the View class. ViewGroup instances work as containers for View instances
to group View instances together. it will act as a base class for layouts and layouts parameters. The ViewGroup
will provide an invisible containers to hold other Views or ViewGroups and to define the layout properties. For
example, Linear Layout is the ViewGroup that contains a UI controls like button, textview, etc. and other layouts
also.
Android contains the following commonly used ViewGroup subclasses:
LinearLayout
RelativeLayout
ListView
GridView
Table Layout
Frame Layout
Web View
These are not the only ViewGroup subclasses Android contains
UI Control Description
TextView This control is used to display text to the user.
EditText EditText is a predefined subclass of TextView that includes rich editing capabilities.
Button A push-button that can be pressed, or clicked, by the user to perform an action.
ImageButton An ImageButton shows a button with an image (instead of text) that can be pressed or clicked by
the user.
CheckBox An on/off switch that can be toggled by the user. You should use check box when presenting
users with a group of selectable options that are not mutually exclusive.
ToggleButton An on/off button with a light indicator.
RadioButton The RadioButton has two states either checked or unchecked.
RadioGroup A RadioGroup is used to group together one or more RadioButtons.
ProgressBar The ProgressBar view provides visual feedback about some ongoing tasks, such as when you
are performing a task in the background.
Spinner A drop-down list that allows users to select one value from a set.
TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM
mode.
DatePicker The DatePicker view enables users to select a date of the day.
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/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file and assign it a unique
ID as follows −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the following −
TextView myText = (TextView) findViewById([Link].text_id);
Common Attributes Used in Views and ViewGroups
Attribute Description
layout_width Specifies the width of the View or ViewGroup
layout_height Specifies the height of the View or ViewGroup
layout_marginTop Specifies extra space on the top side of the View or ViewGroup
layout_marginBottom Specifies extra space on the bottom side of the View or ViewGroup
layout_marginLeft Specifies extra space on the left side of the View or ViewGroup
layout_marginRight Specifies extra space on the right side of the View or ViewGroup
layout_gravity Specifies how child Views are positioned
layout_weight Specifies how much of the extra space in the layout should be
allocated to the View
layout_x Specifies the x-coordinate of the View or ViewGroup
layout_y Specifi es the y-coordinate of the View or ViewGroup
Units of measurement
When specifying the size of an element on an Android UI, you should be aware of
the following units of measurement:
dp — Density-independent pixel. 160dp is equivalent to one inch of physical screen size. This is the
recommended unit of measurement when specifying the dimension of views in your layout. You can specify either
“dp” or “dip” when referring to a density-independent pixel.
sp — Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes.
pt — Point. A point is defi ned to be 1/72 of an inch, based on the physical screen size.
px — Pixel. Corresponds to actual pixels on the screen. Using this unit is not recommended, as your UI may not
render correctly on devices with different screen sizes.
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.
Different events
onClick() - OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You
will use onClick() event handler to handle such event.
onLongClick() - OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for
one or more seconds. You will use onLongClick() event handler to handle such event.
onFocusChange() - OnFocusChangeListener()
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.
onKey() - OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a hardware key on the device. You will
use onKey() event handler to handle such event.
onTouch() - OnTouchListener()
This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use
onTouch() event handler to handle such event.
onMenuItemClick() - OnMenuItemClickListener()
This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such
event.
onCreateContextMenu() - onCreateContextMenuItemListener()
This is called when the context menu is being built.
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 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.
Exmple code :
b1=(Button)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById([Link]);
[Link](25);
}
});
LinearLayout
The LinearLayout arranges views in a single column or a single row. Child views can be arranged either vertically
or horizontally.
Example
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”[Link]
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
</LinearLayout>
In the xml file, observe that the root element is <LinearLayout> and it has
a <TextView> element contained within it. The <LinearLayout> element
controls the order in which the views contained within it appear.
Common Attributes Used in Views and ViewGroups
Attribute Description
layout_width : Specifies the width of the View or
ViewGroup
layout_height :Specifies the height of the View or
ViewGroup
layout_marginTop :Specifies extra space on the top side of the
View or ViewGroup
layout_marginBottom :Specifies extra space on the bottom side of
the View or ViewGroup
layout_marginLeft :Specifies extra space on the left side of the View or ViewGroup
layout_marginRight :Specifies extra space on the right side of the View or ViewGroup
Some of these attributes are applicable only when a View is in a specific ViewGroup. For example, the
layout_weight and layout_gravity attributes are applicable only when a View is in either a LinearLayout or a
TableLayout .
The width of the <TextView> element fi lls the entire width of its parent (which is the screen in this case) using
the fill_parent constant. Its height is indicated by the wrap_content con-stant, which means that its height is the
height of its content
AbsoluteLayout
The AbsoluteLayout enables you to specify the exact location of
its children.
Example :
<?xml version=”1.0” encoding=”utf-8”?>
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=
”[Link]
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px”
/>
<Button
android:layout_width=”113dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”12px”
android:layout_y=”361px”
/>
</AbsoluteLayout>
In AbsoluteLayout as views located at their specified positions using the android_layout_x and android_layout_y
attributes, there will be some problem with the AbsoluteLayout when the activity is viewed on a differnt screen
with differnt resolution. It will not render proposionally. You should avoid using the AbsoluteLayout in your UI,
as it is not guaranteed to be supported in future versions of Android.
TableLayout
The TableLayout groups views into rows and columns. You use the <TableRow> element to designate a row in the
table. Each row can contain one or more views. Each view
you place within a row forms a cell. The width of each
column is determined by the largest width of each cell in that
column.
Example :
<?xml version=”1.0” encoding=”utf-8”?>
<TableLayout
xmlns:android=
”[Link]
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120px”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200px” />
</TableRow>
<TableRow>
<TextView
android:text=”Password:”
/>
<EditText
android:id=”@+id/txtPassword”
android:password=”true”
/>
</TableRow>
<TableRow>
<TextView />
<CheckBox android:id=”@+id/chkRememberPassword”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Remember Password”
/>
</TableRow>
<TableRow>
<Button
android:id=”@+id/buttonSignIn”
android:text=”Log In” />
</TableRow>
</TableLayout>
RelativeLayout
The RelativeLayout enables you to specify how child views are positioned relative to each other or relative to
parent.
Example :
<?xml version=”1.0” encoding=”utf-8”?>
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android= ”[Link]
>
<TextView
android:id=”@+id/lblComments”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Comments”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”/>
<EditText
android:id=”@+id/txtComments”
android:layout_width=”fill_parent”
android:layout_height=”170px”
android:textSize=”18sp”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”/>
<Button
android:id=”@+id/btnSave”
android:layout_width=”125px”
android:layout_height=”wrap_content”
android:text=”Save”
android:layout_below=”@+id/txtComments”
android:layout_alignRight=”@+id/txtComments”/>
<Button
android:id=”@+id/btnCancel”
android:layout_width=”124px”
android:layout_height=”wrap_content”
android:text=”Cancel”
android:layout_below=”@+id/txtComments”
android:layout_alignLeft=”@+id/txtComments”/>
</RelativeLayout>
Notice that each view embedded within the RelativeLayout has attributes that enable it to align with another view.
These attributes are as follows:
layout_alignParentTop
layout_alignParentLeft
layout_alignLeft
layout_alignRight
layout_below
layout_centerHorizontal
Framelayout
The FrameLayout is a placeholder on screen that you can use to display a single view. Views that you add to a
FrameLayout are always anchored to the top left of the layout. Example :
<?xmlversion=”1.0”encoding=”utf-8”?>
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=
”[Link]
>
<TextView
android:id=”@+id/lblComments”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Thisismylovelydog,Ookii”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
/>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
>
<ImageView
android:src=“@drawable/ookii”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
/>
</FrameLayout>
</RelativeLayout>
TextView
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor,
however the basic class is configured to not allow editing.
TextView Attributes
android:id : This is the ID which uniquely identifies the control.
android:capitalize : If set, specifies that this TextView has a textual input method and should automatically
capitalize what the user types.
android:fontFamily : Font family (named by string) for the text.
android:gravity : Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than
the view.
android:hint : Hint text to display when the text is empty.
android:inputType : The type of data being placed in a text field. Phone, Date, Time, Number, Password etc.
android:maxHeight : Makes the TextView be at most this many pixels tall.
android:maxWidth : Makes the TextView be at most this many pixels wide.
android:minHeight : Makes the TextView be at least this many pixels tall.
android:minWidth : Makes the TextView be at least this many pixels wide.
android:password :Whether the characters of the field are displayed as password dots instead of themselves.
Possible value either "true" or "false".
android:text : Text to display.
android:textAllCaps : Present the text in ALL CAPS. Possible value either "true" or "false".
android:textColor : Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb"
android:textIsSelectable : Indicates that the content of a non-editable text can be selected. Possible value either
"true" or "false".
android:textSize : Size of the text. Recommended dimension type for text is "sp" for scaled-pixels
(example: 15sp).
android:textStyle : Style (bold, italic, bolditalic) for the text. You can use or more of the following values
separated by '|'.
android:typeface : Typeface (normal, sans, serif, monospace) for the text. You can use or more of the
following values separated by '|'.
android:text : This is the Text to display.
EditText
A EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of
TextView that includes rich editing capabilities.
Retrieving the Value
Getting the value of the text entered into an EditText is as follows:
EditText simpleEditText = (EditText) findViewById([Link].et_simple);
String strValue = [Link]().toString();
Customizing the Input Type
By default, any text contents within an EditText control is displayed as plain text. By setting inputType, we can
facilitate input of different types of information, like phone numbers and passwords:
<EditText
...
android:inputType="phone">
</EditText>
android:autoText : If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.
android: cursorVisible : Makes the cursor visible (the default) or invisible. Default is false.
android:editable : If set to true, specifies that this TextView has an input method.
android:maxLines : Speciefy the maximum number of line can be entered to the text field
ButtonView
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action. 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.
java program
CheckBox
A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes when presenting
users with a group of selectable options that are not mutually exclusive.
Methods
public boolean isChecked() : Returns true if it is checked otherwise false.
public void setChecked(boolean status) : Changes the state of the CheckBox.
Example
Layout
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pizza"
/>
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Coffee"
/>
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Burger"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order"
/>
java program
RadioButton
A RadioButton has two states: either checked or [Link] allows the user to select one option from a set. In
Android, you can use “[Link]” class to render radio button, and those radio buttons are
usually grouped by [Link]. If RadioButtons are in group, when one RadioButton within a
group is selected, all others are automatically deselected.
You can check the current state of a radio button programmatically by using isChecked() method. This method
returns a Boolean value either true or false.
Checked : checked attribute in radio button is used to set the current state of a radio button.
Gravity : The gravity attribute is an optional attribute which is used to control the alignment of text like
left, right, center, top, bottom, center_vertical, center_horizontal etc.
Padding : padding attribute is used to set the padding from left, right, top or bottom.
PaddingRight : set the padding from the right side of the radio button.
PaddingLeft : set the padding from the left side of the radio button.
PaddingTop : set the padding from the top side of the radio button.
PaddingBottom : set the padding from the bottom side of the radio button.
Padding : set the padding from the all side’s of the radio button.
DrawableBottom :
drawableTop :
drawableLeft :
drawableRight : These attribute draw the drawable to the below of the text of RadioButton.
RadioButton Group
A RadioGroup class is used for set of radio buttons. If we check one radio button that belongs to a radio group,
it automatically unchecks any previously checked radio button within the same group.
Example
Layout File
<RadioGroup
android:id="@+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_male"
android:checked="true" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_female" />
</RadioGroup>
<Button
android:id="@+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_display" />
Java Program
public class MyAndroidAppActivity extends Activity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
addListenerOnButton();
}
ToggleButton
A ToggleButton displays checked/unchecked states as a button. It is basically an on/off button with a light
indicator. Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button. It is
beneficial if user have to change the setting between two states. It can be used to On/Off Sound, Wifi, Bluetooth
etc.
Example
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bluetooth”
android:textOff="Off"
android:textOn="On"
/>
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wifi"
android:textOff="Off"
android:textOn="On"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
/>
Java Program
public class MainActivity extends AppCompatActivity {
ToggleButton simpleToggleButton1, simpleToggleButton2;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// initiate toggle button's
simpleToggleButton1 = (ToggleButton) findViewById([Link].simpleToggleButton1);
simpleToggleButton2 = (ToggleButton) findViewById([Link].simpleToggleButton2);
submit = (Button) findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View view) {
String status = "BlueTooth : " + [Link]() + "\n" + "Wifi : " +
[Link]();
[Link](getApplicationContext(), status, Toast.LENGTH_SHORT).show();
}
});
}
}
ImageButton
In Android, you can use “[Link]” to display a normal “Button“, with a customized
background image. An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its
children. This shows a button with an image (instead of text) that can be pressed or clicked by the user.
android:src This sets a drawable as the content of this ImageView.
android:background : This is a drawable to use as the background.
android:contentDescription : This defines text that briefly describes content of the view.
android:id : This supplies an identifier name for this view
android:on : Click This is the name of the method in this View's context to invoke when the
view is clicked.
android:visibility : This controls the initial visibility of the view.
Example
Layout
<LinearLayout xmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/android_button" />
</LinearLayout>
java program
public class MyAndroidAppActivity extends Activity {
ImageButton imageButton;
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
addListenerOnButton();
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById([Link].imageButton1);
[Link](new OnClickListener() {
@Override
public void onClick(View arg0) {
[Link]([Link],
"ImageButton is clicked!", Toast.LENGTH_SHORT).show();
}
});
}
}
ImageView
Android ImageView is used to display an image file. Android ImageView is one of the UI widget that is used to
display images in the application. It’s defined in the XML layout in the following manner.
ImageView in android comes with different configuration options to support different scaleTypes. ScaleType
options are used for scaling the bounds of an image to the bounds of image view. Below are the listed scaleType
configuration properties supported.
CENTER : Displays the image centered in the view with no scaling.
CENTER_CROP : Scales the image such that both the x and y dimensions are greater than or equal to the view,
while maintaining the image aspect ratio; centers the image in the view
CENTER_INSIDE : Scales the image to fit inside the view, while maintaining the image aspect ratio. If the image
is already smaller than the view, then this is the same as center
FIT_CENTER : Scales the image to fit inside the view, while maintaining the image aspect ratio. At least one axis
will exactly match the view, and the result is centered inside the view
FIT_START : Same as fitCenter but aligned to the top left of the view
FIT_END : Same as fitCenter but aligned to the bottom right of the view
FIT_XY : Scales the x and y dimensions to exactly match the view size. dDoes not maintain the image aspect
ratio
MATRIX : Scales the image using a supplied Matrix class. The matrix can be supplied using the setImageMatrix
method. A Matrix class can be used to apply transformations such as rotations to an image
Example
Lyout File
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/android" />
<Button
android:id="@+id/btnChangeImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Image" />
java source
public class MyAndroidAppActivity extends Activity {
Button button;
ImageView image;
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
addListenerOnButton();
}
public void addListenerOnButton() {
image = (ImageView) findViewById([Link].imageView1);
button = (Button) findViewById([Link]);
[Link](new OnClickListener() {
@Override
public void onClick(View arg0) {
[Link]([Link].android3d);
}
});
}
}
ListView
Android ListView is a view which contains the group of items and displays in a scrollable list. ListView is
implemented by importing [Link] class. ListView is a default scrollable which does not use
other scroll view. The display of elements in a list is a very common pattern in mobile applications. The user sees
a list of items and can scroll through them.
ListView uses Adapter classes which add the content from data source (such as string array, array, database etc) to
ListView. Adapter bridges data between an AdapterViews and other Views (ListView, ScrollView etc).
The input of a list (items in the list) can be arbitrary Java objects. The adapter extracts the correct data from the
data object and assigns this data to the views in the row of the ListView.
These items are typically called the data model of the list. An adapter can receive data as input. An adapter
manages the data model and adapts it to the individual entries in the widget. An adapter extends the BaseAdapter
class. Every line in the widget displaying the data consists of a layout which can be as complex as you want. The
adapter is assigned to the ListView via the setAdapter method on the ListView object. Adapters are not only used
by ListView, but also by other views which extend AdapterView as, for example, Spinner, GridView, Gallery and
StackView.
[Link](new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
[Link](getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
Android provides default adapter implementations; the most important are ArrayAdapter and CursorAdapter.
ArrayAdapter can handle data based on Arrays or [Link]. SimpleCursorAdapter can handle database related
data. The ArrayAdapter class can handle a list or arrays of Java objects as input. Every Java object is mapped to
one row.
final ListView listview = (ListView) findViewById([Link]);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
"OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
"Android", "iPhone", "WindowsMobile" };
Layout File
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
/>
[Link]
<resources>
<string name="app_name">ListView</string>
<string-array name="array_technology">
<item>Android</item>
<item>Java</item>
<item>Php</item>
<item>Hadoop</item>
<item>Sap</item>
<item>Python</item>
<item>Ajax</item>
<item>C++</item>
<item>Ruby</item>
<item>Rails</item>
<item>.Net</item>
<item>Perl</item>
</string-array>
</resources>
java program
listView=(ListView)findViewById([Link]);
textView=(TextView)findViewById([Link]);
listItem = getResources().getStringArray([Link].array_technology);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
[Link].simple_list_item_1, [Link].text1, listItem);
[Link](adapter);
[Link](new [Link]() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// TODO Auto-generated method stub
String value=[Link](position);
[Link](getApplicationContext(),value,Toast.LENGTH_SHORT).show();
}
});
}
}
SpinnerView
In Android, you can use “[Link]” class to render a dropdown box selection list.
Example
File : res/values/[Link]
<string name="app_name">MyAndroidApp</string>
<string name="country_prompt">Choose a country</string>
<string-array name="country_arrays">
<item>Malaysia</item>
<item>United States</item>
<item>Indonesia</item>
<item>France</item>
<item>Italy</item>
<item>Singapore</item>
<item>New Zealand</item>
<item>India</item>
</string-array>
</resources>
LayoutFile
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/country_arrays"
android:prompt="@string/country_prompt" />
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
@Override
public void onClick(View v) {
[Link]([Link],
"OnClickListener : " +
"\nSpinner 1 : "+ [Link]([Link]()) +
"\nSpinner 2 : "+ [Link]([Link]()),
Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Menu in Android
1. Option Menu
2. Context Menu
3. Pop-up Menu
Option Menu
The options menu is the primary collection of menu items for an activity. It's where you should place actions that
have an overall impact on the app, such as Search, Compose Email and Settings.
Context Menu
A context menu is a floating menu that appears when the user performs a long-click on an element. It provides
actions that affect the selected content or context frame.
PopUp Menu
A popup menu displays a list of items in a vertical list that is anchored(stuck) to the view that invoked the menu.
It's good for providing an overflow of actions that relate to specific content or to provide options for a second part
of a command.
Note: Actions in a popup menu should not directly affect the corresponding content—that's what contextual
actions are for. Rather, the popup menu is for extended actions that relate to regions of content in your activity.
How to create a Menu?
For all menu types mentioned above, Android provides a standard XML format to define menu items. Instead of
building a menu in your activity's code, you should define a menu and all its items in an XML menu resource. You
can then inflate the menu resource i.e load the XML files as a Menu object in your activity.
To define the menu_file.xml file, first create a menu directory under res folder. This is done by right clicking on
res --> new --> Android resource directory.
Then a new window will appear. Type menu in the directory name and choose menu in the Resource type. Then,
click on OK.
A new menu directory would be made under res directory. Add menu_file.xml file in menu directory by right
clicking on menu --> New --> Menu resource file.
Give the name as menu_file.xml and click on Ok. The menu_file.xml file contains the following tags:
<menu> It defines a Menu, which is a container for menu items. A <menu> element must be the
root node for the file and can hold one or more <item> and <group> elements.
<item> It creates a MenuItem, which represents a single item in a menu. This element may
contain a nested <menu> element in order to create a submenu.
<group> It is an optional, invisible container for <item> elements. It allows you to categorize menu
items so they share properties such as active state and visibility.
menu_file.xml
The <item> element supports several attributes you can use to define an item's appearance and behavior. The
items in the above menu include the following attributes:
android:id A resource ID that's unique to the item, which allows the application to recognize the item
when the user selects it.
Now, we have understood how to create a [Link] and what does it contain. Let's learn how to use it in our
Activity.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
[Link]([Link].menu_file, menu);
return true;
}
MenuInflater inflater = getMenuInflater(); This gives a MenuInflater object that will be used to
inflate(convert our XML file into Java Object) the menu_file.xml file.
When the user selects an item from the options menu, the system calls your activity's onOptionsItemSelected()
method. This method passes the MenuItem selected. You can identify the item by calling getItemId() method,
which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource). You can
match this ID against known menu items to perform the appropriate action.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection
switch ([Link]()) {
case [Link].i1:
//perform any action;
return true;
case [Link].a:
//perform any action;
return true;
case [Link].b:
//perform any action;
return true;
default:
return [Link](item);
}
}
Note: When you successfully handle a menu item, return true. If you don't handle the menu item, you should call
the superclass implementation of onOptionsItemSelected() (The default implementation returns false).
To make a floating context menu, you need to follow the following steps:
Register the View to which the context menu should be associated by calling registerForContextMenu()
and pass it the View.
If your activity uses a ListView or GridView and you want each item to provide the same context menu, you can
register yout all items for a context menu by passing the ListView or GridView object to
registerForContextMenu() method.
When the registered view receives a long-click event, the system calls your onCreateContextMenu() method. This
is where you define the menu items, usually by inflating a menu resource. For example:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
[Link](menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
[Link]([Link].menu_file, menu);
}
MenuInflater allows you to inflate the menu_file.xml file from a menu resource. The method parameters include
the View that the user selected and aContextMenu. ContextMenuInfo object provides additional information
about the item selected. If your activity has several views such that each provide a different context menu, you
might use these parameters to determine which context menu to inflate.
When the user selects a menu item, the system calls onContextItemSelected() method so that you can perform the
appropriate action. For example:
@Override
public boolean onContextItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link].i1:
//Perform any action;
return true;
case [Link].a:
//Perform any action;
return true;
case [Link].b:
//Perform any action;
return true;
default:
return [Link](item);
}
}
If you have define your menu_file.xml file in XML, here's how you can show the popup menu:
Make an object of PopupMenu, whose constuctor takes the current application Context and the View to
which the menu should be anchored.
Use MenuInflater to inflate your menu resource into the Menu object returned by [Link]()
Call [Link]()
For example, here's a button that shows a popup menu when clicked on it:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="pop" />
The activity can then show the popup menu like this:
To perform an action when the user selects a menu item, you must implement the
[Link] interface to your Activity and register it with your PopupMenu by
calling setOnMenuItemclickListener(). When the user selects an item, the system calls the onMenuItemClick()
method in your Activity.
Example:
Android Code
activity_main.xml
<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am context menu"
android:paddingBottom="30dp"
android:textAllCaps="true"
android:textSize="20sp"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="pop"
android:text="I am Pop Menu"
android:textAllCaps="true"
/>
</LinearLayout>
menu_file.xml
<item android:id="@+id/i1"
android:title="Click me to see sub-menu"
android:icon="@drawable/ic_launcher" >
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
switch ([Link]()){
case [Link].i1:
[Link](this,"Cicked Main Menu",Toast.LENGTH_SHORT).show();
break;
case [Link].i2:
[Link](this,"I am sub-menu 1",Toast.LENGTH_SHORT).show();
break;
case [Link].i3:
[Link](this,"I am sub-menu 2",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, [Link] menuInfo) {
[Link](menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
[Link]([Link].menu_file,menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch ([Link]()){
case [Link].i1:
[Link](this,"Clicked Main menu",Toast.LENGTH_SHORT).show();
break;
case [Link].i2:
[Link](this,"I am sub-menu 1",Toast.LENGTH_SHORT).show();
break;
case [Link].i3:
[Link](this,"I am sub-menu 2",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
public void pop(View v){
PopupMenu popup = new PopupMenu(this,v);
MenuInflater mi = getMenuInflater();
[Link]([Link].menu_file,[Link]());
[Link]();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch ([Link]()){
case [Link].i1:
[Link](this,"Clicked Main menu",Toast.LENGTH_SHORT).show();
break;
case [Link].i2:
[Link](this,"I am sub-menu 1",Toast.LENGTH_SHORT).show();
break;
case [Link].i3:
[Link](this,"I am sub-menu 2",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
Data Persistence
Android, there are primarily three basic ways of persisting data:
A lightweight mechanism known as shared preferences to save small chunks of data
Traditional fi le systems
A relational database management system through the support of SQLite databases
SharedPreferences
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.
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.
To use the SharedPreferences object, you use the getSharedPreferences() method, passing it the name of
the shared preferences file as well as the mode in which it should be opened:
The method is defined as follows:
getSharedPreferences (String PREFS_NAME, int mode)
PREFS_NAME is the name of the file.
mode is the operating mode.
Following are the operating modes applicable:
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
1. contains(String key): This method is used to check whether the preferences contains a
preference.
2. edit(): This method is used to create a new Editor for these preferences, through which you can
make modifications to the data in the preferences and atomically commit those changes back to
the SharedPreferences object.
3. getAll(): This method is used to retrieve all values from the preferences.
4. getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value
from the preferences.
5. getFloat(String key, float defValue): This method is used to retrieve a float value from the
preferences.
6. getInt(String key, int defValue): This method is used to retrieve an int value from the
preferences.
7. getLong(String key, long defValue): This method is used to retrieve a long value from the
preferences.
8. getString(String key, String defValue): This method is used to retrieve a String value from the
preferences.
9. getStringSet(String key, Set: This method is used to retrieve a set of String values from the
preferences.
10. registerOnSharedPreferencechangeListener([Link]
echangeListener listener): This method is used to registers a callback to be invoked when a
change happens to a preference.
11. unregisterOnSharedPreferencechangeListener([Link]
ncechangeListener listener): This method is used to unregisters a previous callback
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
[Link](“FONT_SIZE”, [Link]());
[Link](“TEXT_VALUE”, [Link]().toString());
[Link]();
The MODE_PRIVATE constant indicates that the shared preference file can only be opened by the
application that created it. The Editor class allows you to save key/value pairs to the preferences file by
exposing methods such as the following putString(), putBoolean(), putLong(). When you are done
saving the values, call the commit() method to save the changes
To read values from SharedPreferences you first obtain the SharedPreferences object and then retrieve
all the values saved earlier:
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
[Link]();
[Link](); // commit changes
openFileOutput(): This method is used to create and save a file. Its syntax is given below:
The method openFileOutput() returns an instance of FileOutputStream. After that we can call
write method to write data on the file. Its syntax is given below:
String str = "test data";
[Link]([Link]());
[Link]();
openFileInput(): This method is used to open a file and read it. It returns an instance of
FileInputStream. Its syntax is given below:
FileInputStream fin = openFileInput(file);
After that, we call read method to read one character at a time from the file and then print it. Its
syntax is given below:
int c;
String temp="";
while( (c = [Link]()) != -1){
temp = temp + [Link]((char)c);
}
[Link]();
In the above code, string temp contains all the data of the file.
Note that these methods do not accept file paths (e.g. path/to/[Link]), they just take simple file
names.
To save text into a file, you use the FileOutputStream class. The openFileOutput() method opens a
named file for writing, with the mode specified. The MODE_PRIVATE constant to indicate that file
can only be accessed by the application that created it :
Apart from the MODE_WORLD_READABLE constant, you can select from the following:
MODE_WORLD_READABLE (the file is readable by all other applications), MODE_APPEND (for
appending to an existing file), and MODE_WORLD_WRITEABLE (all other applications have write
access to the file).
To convert a character stream into a byte stream, you can also use an instance of the OutputStreamWriter
class,by passing it an instance of the FileOutputStream object:
OutputStreamWriter osw = newOutputStreamWriter(fOut);
You then use its write() method to write the string to the file. To ensure that all the bytes are written to
the file, use the flush() method. Finally, use the close() method to close the file:
[Link](str);
[Link]();
[Link]();
To read the content of a file, you use the FileInputStream class, together with the InputStreamReader
class:
FileInputStream fIn = openFileInput(“[Link]”);
InputStreamReader isr = new InputStreamReader(fIn);
As you do not know the size of the file to read, the content is read in blocks of 100 characters into a
buffer (character array). The characters read are then copied into a String object:
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = “”;
int charRead;
while ((charRead = [Link](inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
[Link](inputBuffer, 0,
charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
The read() method of the InputStreamReader object reads the number of characters read and returns
-1 if the end of the file is reached.
Android External Storage – Read, Write, Save File
Android external storage can be used to write and save data, read configuration files etc. External
storage such as SD card can also store application data, there’s no security enforced upon files you save
to the external storage.
In general there are two types of External Storage:
Primary External Storage: In built shared storage which is “accessible by the user by plugging
in a USB cable and mounting it as a drive on a host computer”. Example: When we say Nexus 5
32 GB.
Secondary External Storage: Removable storage. Example: SD Card
All applications can read and write files placed on the external storage and the user can remove them.
We need to check if the SD card is available and if we can write to it. Once we’ve checked that the
external storage is available only then we can write to it else the save button would be disabled.
Firstly, we need to make sure that the application has permission to read and write data to the users SD
card, so lets open up the [Link] and add the following permissions:
<uses-permission android:name="[Link].WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="[Link].READ_EXTERNAL_STORAGE"/>
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
[Link](false);
}
try {
fileOutputStream = new FileOutputStream(myFile);
[Link]([Link]());
[Link](this, "Done" + [Link](), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
[Link]();
} finally {
if (fileOutputStream != null) {
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
Android SQLite
Android SQLite is a very lightweight database which comes with Android OS. Android SQLite combines a clean
SQL interface with a very small memory footprint and decent speed. For Android, SQLite is “baked into” the
Android runtime, so every Android application can create its own SQLite databases.
Android SQLite native API is not JDBC, as JDBC might be too much overhead for a memory-limited
smartphone. Once a database is created successfully its located in data/data//databases/ accessible from Android
Device Monitor.
SQLite is a typical relational database, containing tables (which consists of rows and columns), indexes etc. We
can create our own tables to hold the data accordingly. This structure is referred to as a schema.
1. When the application runs the first time – At this point, we do not yet have a database. So we will have to
create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema – Our database will still be on the old schema from
the older edition of the app. We will have option to alter the database schema to match the needs of the
rest of the app.
SQLiteOpenHelper wraps up these logic to create and upgrade a database as per our specifications. For that we’ll
need to create a custom subclass of SQLiteOpenHelper implementing at least the following three methods.
1. Constructor : This takes the Context (e.g., an Activity), the name of the database, an optional cursor
factory (we’ll discuss this later), and an integer representing the version of the database schema you are
using (typically starting from 1 and increment later).