0% found this document useful (0 votes)
15 views91 pages

Module - 3: Semester Vi Bcs/Bca S.A

The document provides an overview of Android User Interfaces, detailing various UI components such as Views, ViewGroups, and common controls like TextView, EditText, Buttons, CheckBoxes, and RadioButtons. It explains how to create and manage these components using XML and Java code, highlighting their properties and methods. Additionally, it covers the usage of Date and Time controls in Android applications.

Uploaded by

santamariya474
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views91 pages

Module - 3: Semester Vi Bcs/Bca S.A

The document provides an overview of Android User Interfaces, detailing various UI components such as Views, ViewGroups, and common controls like TextView, EditText, Buttons, CheckBoxes, and RadioButtons. It explains how to create and manage these components using XML and Java code, highlighting their properties and methods. Additionally, it covers the usage of Date and Time controls in Android applications.

Uploaded by

santamariya474
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Module – 3

SEMESTER VI BCS/BCA
S.A
Android User Interfaces
➢ The graphical user interface is an interface that allows users to
interact with electronic devices through graphical icons and
visual indicators.
➢ User Interface is everything that user can see and interact with.
Android supports pre-built UI components such as structured
layout objects and UI controls.
➢ A view is an object that draws something on the screen.
➢ A ViewGroup is an object that holds other ViewGroups and
view objects. It is an invisible container that organizes other
child views.
➢ UI can be built using three methods – building UI using code,
building UI using XML, building UI using code and XML
View is the base class for widgets, which are used to create interactive UI
components like buttons, text fields, etc. View is a basic building block of UI
(User Interface) in android. A view responds to user inputs. Eg: EditText, Button,
CheckBox, etc. ViewGroup is an invisible container of other views (child views)
and other ViewGroup. Eg: LinearLayout is a ViewGroup that can contain other
views in it. View refer to the android.view.View class, which is the base class of
all UI classes.
1. Understanding
Android’s Common Controls
➢ Views include text controls and then cover buttons, check boxes, radio
buttons, lists, grids, date and time controls, and a map-view control.

a). Text Controls


➢Text controls is a user interface control in
Android.
➢Android has a complete set of text controls.
➢It includes TextView, EditText,
AutoCompleteTextView, and
MultiCompleteTextView controls.
I). TextView
➢The TextView control displays text but it does not allow editing.
➢In TextView autoLink property can be set to email|web, and the control
will find and highlight any e-mail addresses and URLs.
➢When the user clicks on one of these highlighted items, the system will
take care of launching the e-mail application with the e-mail address, or a
browser with the URL.
➢In XML, this attribute would be inside the TextView tag and would
look something like this:
<TextView
android:autoLink="email|web“
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content“
android:text="ename" />
➢If you want to set autoLink behavior in code instead of using XML,
the corresponding method call is setAutoLinkMask().
➢To achieve this functionality, TextView is utilizing the
android.text.util.Linkify class.
➢example of auto-linking with code.
TextView tv =(TextView)this.findViewById(R.id.tv);
tv.setAutoLinkMask(Linkify.ALL);
tv.setText("Please visit my website, http://www.androidbook.com
or email me at [email protected].");
II). EditText
➢The EditText control is a subclass of Text Field.
➢As suggested by the name, the EditText control allows for text editing.
➢Significant properties of an EditText is the inputType.
➢You can set the inputType property to textAutoCorrect have the control
correct common misspellings.
➢You can set it to textCapWords to have the control capitalize words.
➢Other options expect only phone numbers or passwords.
➢The old default behavior of the EditText control is to display text on
one line and expand as needed.
➢You could, however, force the user to a single line by setting the
singleLine property to true.
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/name"
android:inputType="text" />

Most common inputTypes include:

Type Description
Text that is a password that should be
textPassword
obscured from others.
textVisiblePassword Text
number A numeric only field
phone For entering a phone number
date For entering a date
time For entering a time
textMultiLine Allow multiple lines of text in the field
➢If multiline typing is required, you need to specify inputType with
textMultiLine.
➢One of the nice features of EditText is that you can specify hint text.
➢This text will be displayed slightly faded and disappears as soon as the
user starts to type text.
➢The purpose of the hint is to let the user know what is expected in this
field, without the user having to select and erase default text.
➢In XML, this attribute is android:hint="your hint text here" or
android:hint="@string/your_hint_name", where your_hint_name is a
resource name of a string to be found in /res/values/strings.xml.
III). AutoCompleteTextView
➢The AutoCompleteTextView control is a TextView with auto-complete
functionality.
➢In other words, as the user types in the TextView, the control can
display suggestions for selection.
<AutoCompleteTextView
android:id="@+id/actv“
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
IV). MultiAutoCompleteTextView
➢In Android, MultiAutoCompleteTextView is an
editable TextView extends AutoCompleteTextView that can show the
complete suggestion for the sub-string of a text allowing user to quickly
select instead of typing whole.
➢One most important difference between
MultiAutoCompleteTextView and AutoCompleteTextView is that
AutoCompleteTextView can hold or select only single value at single
time but MultiAutoCompleteTextView can hold multiple string words
value at single time.
➢ These all values are separated by comma(,).

Example :-

<MultiAutoCompleteTextView
android:id="@+id/mactv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
b). Button Controls
➢Buttons are common in any widget toolkit.
➢Android offers the typical set of buttons as well as a few extras.
➢In this section, we will discuss three types of button controls:
❖ basic button
❖ image button
❖ toggle button.
➢The button at the top is the basic button, the
➢middle button is an image button, and the last one is a toggle button.
I). The Button Control
➢The basic button class in Android is android.widget.Button.
➢There’s not much to this type of button, beyond how you use it to
handle click events.
Handling Click Events on a Button :-
<Button
android:id="@+id/button1"
android:text="@string/basicBtnLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Java Code

Button button1 = (Button)this.findViewById(R.id.button1);


button1.setOnClickListener(new OnClickListener()
public void {onClick(View v)
{
//code }
});
II). The ImageButton Control
➢Android provides an image button via android.widget.ImageButton.

<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClickHandler"
android:src="@drawable/icon" />

➢Here we’ve created the image button in XML and set the button’s
image from a drawable resource.
➢The image file for the button must exist under /res/drawable.
III). The ToggleButton Control
➢The ToggleButton control, like a check box or
a radio button, is a two-state button.
➢ToggleButton’s default behavior is to show a
green bar when in the On state and a grayed-out
bar when in the Off state.

➢Moreover, the default behavior also sets the button’s text to On when
it’s in the On state and Off when it’s in the Off state.
➢You can modify the text for the ToggleButton if On/Off is not
appropriate for your application.
➢For example, if you have a background process that you want to start
and stop via a ToggleButton, you could set the button’s text to Stop and
Run by using android:textOn and android:textOff properties.
➢This button can be in either the On or Off state.
➢ToggleButton’s default behavior is to show a green bar when in the
On state and a grayed-out bar when in the Off state.
<ToggleButton
android:id="@+id/cctglBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle Button"
android:textOn="Stop"
android:textOff="Run"/>
c). The CheckBox Control
➢A CheckBox is an on/off switch that can
be toggled by the user. Using checkbox
user can select multiple options at a time.
➢You should use check-boxes when
presenting users with a group of selectable
options that are not mutually exclusive.
➢For example, it can be used to know the
hobby of the user, activate/deactivate the
specific action etc.
➢In Android, you can create a check box
by creating an instance of
android.widget.CheckBox.
Attributes of Checkbox :-
Attribute Description
If set, specifies that this TextView has a
android:autoText textual input method and automatically
corrects some common spelling errors.
android:text This is the Text to display.
This is the name of the method in this
android:onClick View's context to invoke when the
view is clicked.
This controls the initial visibility of the
android:visibility
view.
Methods of Checkbox :-
Method Description

public boolean isChecked() Returns true if it is checked otherwise


false.

public void setChecked(boolean status) Changes the state of the CheckBox.

➢You manage the state of a check box by calling setChecked() or


toggle().
➢You can obtain the state by calling isChecked().
➢If you need to implement specific logic
when a check box is checked or unchecked,
you can register for the on-checked event by
calling setOnCheckedChangeListener()
with an implementation of the
OnCheckedChangeListener interface.
➢You’ll then have to implement the
onCheckedChanged() method, which will
be called when the check box is checked or
unchecked.
➢Android CheckBox class is the subclass
of CompoundButton class.
Example of Check Box :-
Activity_main.xml
<CheckBox
android:id="@+id/ch_b1"
android:text="Chicken"
android:checked="true"
android:layout_width=“wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="@+id/ch_b2"
android:text="Fish“
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="@+id/ch_b3"
android:text="Steak"
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
d). The RadioButton Control
➢Radio buttons are normally used together in a RadioGroup.
RadioButton is mutually exclusive. Only one radiobutton can be
selected at a time.
➢When several radio buttons live inside a radio group, checking one
radio button will unchecks all the others.
➢we will use “android.widget.RadioButton” class to render radio
button, and those radio buttons are usually grouped by
android.widget.RadioGroup.
Attributes of RadioButton :-
Attribute Description
android:id This supplies an identifier name for this view

android:onClick 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.


➢You can also use the toggle() method to toggle the state of the radio
button.
➢As with the CheckBox control, you will be notified of on-checked
or on-unchecked events if you call the
setOnCheckedChangeListener() with an implementation of the
OnCheckedChangeListener interface.
➢We can always get the currently checked RadioButton using
getCheckedRadioButtonId(), which returns the resource ID of the
checked item or –1 if nothing is checked.
➢clearCheck() method is used to clear the selection of Radio Buttons.
Example of RadioButton :-
Activity_main.xml
<RelativeLayout
<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"
android:layout_marginTop="20dp"/>
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_female" />
</RadioGroup>
Outputs :-
e). The ImageView Control
➢ImageView control is used to display an image, where the image can
come from a file, a content provider, or a resource such as a drawable.
➢“android.widget.ImageView” class can be used to display an image
file.
➢Image file is easy to use but hard to adapt, because of the various
screen and dpi in Android devices.
➢Images are kept into folder “res/drawable-ldpi“, “res/drawable-
mdpi” or “res/drawable-hdpi“.
ldpi
image folder for Lower images quality which supports by the earlier
sets of the android
mdpi
image folder for medium images support
hdpi
image folder maintain images for the Android Broad Screen set or
Android Phones with the Higher resolution.
xhdpi
image folder for devices with large resolution.
xxhdpi
image folder for devices extra large devices/ maximum resolution(Like
Google Nexus 10 need to add a 144*144px icon in the drawable-
xxhdpi or drawable-480dpi folder.)
Sample Codes
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon“
/>
<ImageView
android:id="@+id/image3"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
/>
<ImageView
android:id="@+id/image4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/manatee02"
android:scaleType="centerInside"
android:maxWidth="35dip" android:maxHeight="50dip"
/>
Java Codes
ImageView imgView = (ImageView)findViewById(R.id.image3);

Attributes of ImageView Control :-

android:maxHeight
An optional argument to supply a maximum height for this view.
android:maxWidth
An optional argument to supply a maximum width for this view.
android:src
Sets a drawable as the content of this ImageView.
Methods of ImageView Control :-
❖public void setImageBitmap(Bitmap bm)
➢Sets a Bitmap as the content of this ImageView.

❖public void setImageDrawble(Drawble drawble)


➢Sets a drawable as the content of this ImageView.

❖public void setMaxHeight(int maxHeight)


➢An optional argument to supply a maximum height for this view.

❖public void setMaxWidth(int maxWidth)


➢An optional argument to supply a maximum width for this view.
f). Date and Time Controls
➢Date and time controls are common in many
widget toolkits. Android offers several date- and
time-based controls.
❖ DatePicker
❖ TimePicker
❖ DigitalClock
❖ AnalogClock
1. Date Picker
➢Android Date Picker allows to select the date consisting of day,
month and year in your custom user interface.
➢For this functionality android provides DatePicker and
DatePickerDialog components.
➢DatePickerDialog is a simple dialog containing DatePicker.
Method Description
getDayOfMonth() This method gets the selected day of month
getMonth() This method gets the selected month
getYear() This method gets the selected year
setMaxDate(long This method sets the maximal date supported by
maxDate) this DatePicker in milliseconds since January 1,
1970 00:00:00 in getDefault() time zone

setMinDate(long This method sets the minimal date supported by


minDate) this NumberPicker in milliseconds since January
1, 1970 00:00:00 in getDefault() time zone
Method Description

updateDate(int year, int This method updates the current date


month, int
dayOfMonth)

getCalendarView() This method returns calendar view

getFirstDayOfWeek() This Method returns first day of the week


Activity_main.xml

<LinearLayout >
<TextView
android:id="@+id/dateDefault"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
2. Time Picker
➢Android Time Picker allows you to select the time of day in either
24 hour or AM/PM mode.
➢The time consists of hours, minutes and clock format.
➢Android provides this functionality through TimePicker class.
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Method Description
is24HourView() This method returns true if this is in 24
hour view else false
isEnabled() This method returns the enabled status
for this view
setCurrentHour(Integer This method sets the current hour
currentHour)
setCurrentMinute(Integer This method sets the current minute
currentMinute)
setEnabled(boolean enabled) This method set the enabled state of this
view
setIs24HourView(Boolean This method set whether in 24 hour or
is24HourView) AM/PM mode
setOnTimeChangedListener(TimePi
cker.OnTimeChangedListener This method Set the callback that
onTimeChangedListener) indicates the time has been adjusted by
the user
3. Analog and Digital Clock Control
➢In Android, the AnalogClock is a two-handed clock, one for hour
indicator and the other for minute indicator.
➢ The DigitalClock is look like your normal digital watch on hand,
which display hours, minutes and seconds in digital format.
➢Both AnalogClock and DigitalClock are UNABLE to modify the
time, if you want to change the time, use “TimePicker” instead.

<AnalogClock
android:id="@+id/analogClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<DigitalClock
android:id="@+id/digitalClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DigitalClock" />
g ). Map View Controls
➢The com.google.android.maps.MapView control can display a map.
➢This control can be instantiated either via XML layout or code, but
the activity that uses it must extend MapActivity.
➢MapActivity takes care of multithreading requests to load a map,
perform caching, and so on.
<LinearLayout
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="myAPIKey"
/>
</LinearLayout>
• Map Controls API has attributes such as UI Controls, Zoom
controls that appears in the right bottom corner of the
application.
• It also has compass graphic that appears in the top left corner
of the app.
• Map Control also includes Map gestures, My Location, Map
Tool bar etc.
Understanding Adapters
➢List controls (AdapterViews) are used to display collections of
data. Adapters are bridge between AdapterView [ListView, GridView]
and underlying data for that view.

➢Some Adapters are –

➢ArrayAdapter
➢CursorAdapter
➢SimpleAdapter
➢SimpleCursorAdapter
AdapterView Class hierarchy
Adapter and AdapterView
➢ Adapter View handles the data display.
➢ AdapterView class is inherited from ViewGroup class.
AdapterView are classes that extend
android.widget.AdapterView
➢ AdapterView includes ListView, GridView, Spinner Class
etc.
➢ Adapter class manages data for an AdapterView and
provides child view for it.
➢ Adapters are the link between a set of data and the
AdapterView.
➢ Adapter retrieves data from a source such as array or
database and converts each data into view that can be added
into Adapter View layout.
Types of Adapters

1.SimpleCursorAdapter
➢The SimpleCursorAdapter links the data contained in a Cursor to an
Adapter View.
Cursors
❖A cursor is a set of data.
❖A cursor is returned when a database query is executed .
❖The result of your query is contained in the cursor.
❖The SimpleCursorAdapter binds the Cursor data to an
Adapter View.
❖ You define a layout that controls how each row of data is
displayed.
❖This layout is then displayed in the Adapter View, like a
ListView for example.
Cursor
SimpleCurserAdapter
➢To map the data rows to the ListView, the SimpleCursorAdapter
needs to have a child layout resource ID.
➢The constructor of SimpleCursorAdapter looks like this:
SimpleCursorAdapter(Context context, int childLayout, Cursor
c, String[] from, int[] to)
➢This adapter converts a row from the cursor to a child view for the
container control.
➢The definition of the child view is defined in an XML resource
(childLayout parameter).
➢Context :- The context where the ListView associated with this
SimpleListItem is running
➢Layout :- Resource identifier of a layout file that defines the views
for this list item.
➢C :- The database cursor. Can be null if the cursor is not available
yet.
➢From :- A list of column names representing the data to bind
to the UI.
➢To :- The views that should display column in the "from"
parameter.
2.ArrayAdapter

➢In Android development, any time we want to show a vertical list of


scrollable items we will use a ListView .
➢The simplest adapter to use is called an ArrayAdapter because the
adapter converts an ArrayList of objects into View items loaded into
the ListView container.
➢The ArrayAdapter is the simplest of the adapters in Android.
➢The ArrayAdapter fits in between an ArrayList (data source) and
the ListView (visual representation).
➢To use a basic ArrayAdapter, you just need to initialize the adapter
and attach the adapter to the ListView. First, we initialize the adapter:

ArrayAdapter<String> itemsAdapter = new ArrayAdapter <String>


(this, android.R.layout.simple_list_item_1, items);

➢The ArrayAdapter requires a declaration of the type of the item to be


converted to a View (a String in this case) and then accepts three
arguments:
o this :- context (activity instance)
o simple_list_itmes_1:- XML item layout
o items :- the array of data.
Example of ArrayAdapter :-
Activity_main.xml
<LinearLayout>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff1111cc"
android:textStyle="bold"
android:layout_marginTop="10dp"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="multipleChoice"/>
</LinearLayout>
AdapterViews
1. The Basic List Control: ListView
➢Android ListView is a view which groups
several items and display them in vertical
scrollable list.
➢The list items are automatically inserted to
the list using an Adapter that pulls content
from a source such as an array or database.
➢An adapter actually bridges between UI
components and the data source that fill data
into UI Component.
➢Adapter holds the data and send the data to
adapter view, the view can takes the data
from adapter view and shows the data on
different views like as spinner, list view, grid
view etc.
➢The ListView and GridView are subclasses of AdapterView and
they can be populated by binding them to an Adapter, which
retrieves data from an external source and creates a View that
represents each data entry.
➢Android provides several subclasses of Adapter that are useful for
retrieving different kinds of data and building views for an AdapterView
( i.e. ListView or GridView).
➢The common adapters are
❖ ArrayAdapter
❖ BaseAdapter
❖ CursorAdapter
❖ SimpleCursorAdapter
❖ SpinnerAdapter
❖ WrapperListAdapter
Displaying Values in a ListView
➢You can use this adapterview when your data source is an array.
➢By default, ArrayAdapter creates a view for each array item by calling
toString() on each item and placing the contents in a TextView.
➢ Consider you have an array of strings you want to display in a
ListView, initialize a new ArrayAdapter using a constructor to specify
the layout for each string and the string array −
ArrayAdapter adapter = new ArrayAdapter <String>
(this,R.layout.ListView, StringArray);
➢Once you have array adapter created, then simply call setAdapter() on
your ListView object as follows −

ListView listView = (ListView) findViewById(R.id.listview);


listView.setAdapter(adapter);
Example of ListView :-
Activity_main.xml
<LinearLayout>
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
2. Grid View Control
➢Android GridView shows items in two-
dimensional scrolling grid (rows & columns).
➢ Grid items are not necessarily
predetermined but they automatically inserted
to the layout using a ListAdapter.
Following are the important attributes specific to GridView −
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:columnWid This specifies the fixed width for each column.
th This could be in px, dp, sp, in, or mm.
Specifies the gravity within each cell.
android:gravity Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.
android:horizontalS Defines the default horizontal spacing between columns.
pacing This could be in px, dp, sp, in, or mm.
Defines how many columns to show.
android:numColum May be an integer value, such as "100" or auto_fit which
ns means display as many columns as possible to fill the
available space.
Defines how columns should stretch to fill the
android:stretchMode available empty space, if any. This must be either of
the values −
•none − Stretching is disabled.
•spacingWidth − The spacing between each column
is stretched.
•columnWidth − Each column is stretched equally.
•spacingWidthUniform − The spacing between each
column is uniformly stretched..

Defines the default vertical spacing between rows.


android:verticalSpacing This could be in px, dp, sp, in, or mm.
Example of GridView :-
Activity_main.xml
<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10px"
android:verticalSpacing="10px"
android:horizontalSpacing="10px"
android:numColumns="auto_fit"
android:columnWidth="100px"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Output :-
3. Spinner Control
➢The Spinner control is like a drop-down
menu.
➢It is typically used to select from a
relatively short list of choices.
➢If the choice list is too long for the display,
a scrollbar is automatically added.
➢Spinners provide a quick way to select one
value from a set.
➢In the default state, a spinner shows its
currently selected value.
➢Touching the spinner displays a dropdown
menu with all other available values, from
which the user can select a new one.
Example of Spinner :-

Activity_main.xml
<LinearLayout>
<Spinner
android:id="@+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/hello_world"
/>
</LinearLayout>
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
public class MainActivity extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp = (Spinner)findViewById(R.id.planets_spinner);
String[] items = { "this", "is", "a", "really", "silly", "list" };
ArrayAdapter<String> ad = new ArrayAdapter
<String>(this,android.R.layout.simple_list_item_1,items);
sp.setAdapter(ad);
}}
Output :-
4. Gallery Control
➢The Gallery control is a horizontally
scrollable list control that always focuses at
the center of the list.
➢This control generally functions as a photo
gallery in touch mode.
➢The Gallery control is typically used to
display images.
➢Gallery can be Instantiated via either XML
layout or code:
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content />
Styles and Themes
➢Android provides several ways to alter the style of views in your
application.
➢We’ll first cover using markup tags in strings and then how to use
spannables to change specific visual attributes of text.
1. Styles
➢A style is a collection of View attributes that is given a name.
➢A style can be applied to a view or to an entire activity.
➢ That collection can be referred by its name.
➢Style can be applied statically or dynamically.
➢Statically, you can apply markup directly to the strings in your string
resources, as shown here:
➢You can then reference it in your XML or from code. Note that you
can use the following
➢HTML tags with string resources:
❖ <i>, <b>, <u>, <strike>, <big>, <small>, <monospace>
<string name="styledText"><i>Static</i> style in
<b>TextView</b>
.</string>
➢A style is a collection of View attributes that is given a name
➢ The collection can be referred by its name and assign that style by
name to views.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ErrorText">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#FF0000</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
➢We can now use this style for a TextView, as shown

<TextView
android:id="@+id/errorText"
style="@style/ErrorText"
android:text="No errors at this time"/>

➢Styling a TextView control’s content programmatically requires a


little additional work but allows for much more flexibility, because you
can style at runtime.
➢Spannable is basically a String that you can apply styles to.
2. Themes
➢One problem with styles is that it is needed to add an attribute
specification of style="@style/..." to every view definition that you
want it to apply to.
➢If you have some style elements to be applied across an entire
activity, or across the whole application, theme should be used
instead.
➢A theme is really just a style applied broadly.
➢In fact, themes and styles are fairly interchangeable.
➢To specify a theme for an activity or an application, add an attribute
to the <activity> or <application> tag in the AndroidManifest.xml file
of the project.
➢The code might look like one of these:

<activity android:theme="@style/MyActivityTheme">
<application android:theme="@style/MyApplicationTheme">
<application android:theme="@android:style/Theme.NoTitleBar">
Understanding Layout Managers
➢Android offers a collection of view classes that act as containers for
views.
➢These container classes are called layouts (or layout managers), and
each implements a specific strategy to manage the size and position of its
children – [child views].
Layout Manager Description
LinearLayout Organizes its children either
horizontally or vertically
TableLayout Organizes its children in tabular form
RelativeLayout Organizes its children relative to one
another or to the parent
FrameLayout Allows you to dynamically change the
control(s) in the layout
GridLayout Organizes its children in a grid
arrangement
1. The LinearLayout Layout Manager
➢The LinearLayout layout manager is the most basic layout.
➢ This layout manager organizes its children either horizontally or
vertically based on the value of the orientation property.
➢LinearLayout with a horizontal configuration.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- add children here-->


<!-- add children here-->

</LinearLayout>
2. The TableLayout Layout Manager
➢The TableLayout layout manager is an extension of LinearLayout.
➢This layout manager structures its child controls into rows and
columns.
Example of Simple Table Layout :-
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow>
<TextView
android:text="First Name:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:text="Edgar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="Last Name:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:text="Poe"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>

➢To use this layout manager, you create an instance of TableLayout and
place TableRow elements within it.
➢These TableRow elements contain the controls of the table.
Output :-
Example Using android:padding :-
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:text="one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="40px" />
</LinearLayout>
➢This creates 40 pixels of whitespace between the EditText control’s
outer boundary and the text displayed within it.
➢android:padding sets the padding for all sides: left, right, top, and
bottom.
➢You can control the padding for each side by using android:
leftPadding , android:rightPadding, android:topPadding, and
android:bottomPadding.
3. The RelativeLayout Layout Manager
➢One of the most important layout manager is RelativeLayout.
➢As the name suggests, this layout manager implements a policy
where the controls in the container are laid out relative to either the
container or another control in the container.
Example of Relative Layout :-

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<TextView
android:id="@+id/userNameLbl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Username: " />
<EditText
android:id="@+id/userNameText"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/pwdCriteria"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</RelativeLayout>
4. The FrameLayout Layout Manager
➢Android also offers a layout manager that is
mainly used to display a single item:
FrameLayout.
➢ This utility layout class is mainly used to
dynamically display a single view, but it can
be populatde it with many items, by setting
one to visible while the others are invisible.
Example of Frame Layout :-

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frmLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/oneImgView"
android:src="@drawable/one"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<ImageView
android:id="@+id/twoImgView"
android:src="@drawable/two"
android:scaleType="fitCenter"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone" />
</FrameLayout>
Output :-
5. The GridLayout Layout Manager
➢Android 4.0 brought with it a new
layout manager called GridLayout.
➢GridLaout lays out views in a grid
pattern of rows and columns,
somewhat like TableLayout.
➢Views can span multiple grid cells.
More than one view can be put into
the same grid cell.

You might also like