Escolar Documentos
Profissional Documentos
Cultura Documentos
Adapters are the link between a set of data and the AdapterView that displays the data.
AdapterView
AdapterViews are ViewGroups that display child views given to it by an adapter. An example of
an AdapterView is a ListView.
Adapters also provide the child views that display the data in the AdapterView.
Adapters are responsible for supplying the data and creating the views representing
each item.
This is a very important picture to understand. On the left side is the AdapterView; in this
example, it is a ListView made up of TextView children. On the right side is the data; in this
example, its represented as a result set of data rows that came from a query against a content
provider. To map the data rows to the ListView, the SimpleCursorAdapter needs to have a child
layout resource ID. The child layout must describe the layout for each of the data elements from
the right side that should be displayed on the left side. For example, if you have a result set of
information from the Contacts content provider, and you only want to display each contact name
in your ListView, you would need to provide a layout to describe what the name field should
look like. If you wanted to display the name and an image from the result set in each row of the
ListView, your layout must say how to display the name and the image.
The SimpleCursorAdapter links the data contained in a Cursor to an Adapter View.
Cursors
A cursor is a set of data. You usually get a cursor when you do a database query. 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. Each rows
view is populated using the column values of the corresponding row in the cursor. This layout is
then displayed in the Adapter View, like a ListView for example.
The simplest constructor of SimpleCursorAdapter looks like this:
SimpleCursorAdapter(Context context, int childLayout, Cursor c, String[] from, int[] to)
Context- current application context/running environment
Child Layout-Layout for the row
From array-specify the column names in the cursor from the row which you want to select.
To array-array of child layout ID
Each column you select must be mapped to a View in the layout, you must specify the IDs in the
to parameter. Theres a one-to-one mapping between the column you select and a View that
displays the data in the column, so the from and to parameter arrays must have the same number
of elements. When the ListView wants to display a row of data, it calls the getView() method of
the adapter, passing in the position to specify the row of data to be displayed. The adapter
responds by building the appropriate child view using the layout that was set in the adapters
constructor and by pulling the data from the appropriate record in the result set.
Array Adapter
Array adapter is an adapter backed up by an array. It links the array to the adapter view. The
default ArrayAdapter converts an array item into a String object putting it into a TextView. The
text view is then displayed in the AdapterView.
Creating a new ArrayAdapter can look as simple as this:
ArrayAdapter allows for dynamic modifications to the underlying data. For example, the
add() method will append a new value on the end of the array. The insert() method will
add a new value at a specified position within the array. And remove() takes an object out
of the array. You can also call sort() to reorder the array.
Of course, once youve done this, the data array is out of sync with the ListView, so thats
when you call the notifyDataSetChanged() method of the adapter. This method will
resync the ListView with the adapter.
List View
Android provides the ListView class which is capable of displaying a scrollable list of items. if
weve got a list of items to view and the number of items extends beyond what we can currently
see in the display, we can scroll to see the rest of the items. Generally use a ListView by writing
a new activity that extends android.app.ListActivity. ListActivity contains a ListView, and you
set the data for the ListView by calling the setListAdapter() method.
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
The following listing shows the java code for the activity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
private ListView listView1 = (ListView) findViewById(R.id.listView1);
creating a list view reference of type ListView class
String[] someColors = new String[] { "Red", "Orange", "Yellow",
"Green", "Blue", "Indigo", "Violet", "Black", "White"};
creating an String array to store the data for the adapter which is to be displayed in
the ListView
ArrayList<String> colorArrayList = new ArrayList<String>();
creating a ListArray to store a String Array of Values/data
colorArrayList.addAll( Arrays.asList(someColors) );
add new elements into the ArrayList via the add() method or a Collection via
the addAll() method. Here we need to add a collection of data via addAll() method.
private ArrayAdapter<String> listAdapter1 = new ArrayAdapter<String>(this,android.R.id.text1,
colorArrayList);
creating ArrayAdapter which containd the default layout and array of data
listView1.setAdapter( listAdapter1 );
Linking the adapter with the adapter view(ListView) using the setAdapter method
}
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itenValue=(String)listView1.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
itemValue, Toast.LENGTH_LONG)
.show();
}});
Our activity is now implementing the OnItemClickListener interface, which means well
receive a callback when the user clicks something in our ListView.
Using the method onItemClick() method, we get a lot of information about what was
clicked, including the view receiving the click, the position of the clicked item in the
ListView, and the ID of the item according to our adapter.
We display those informations using a Toast by implementing makeText() method. The
position value represents where this item is in relation to the overall list of items in the
ListView, and its zero-based.
Therefore, the first item in the list is at position 0.
Adding another control along with the ListView is done using xml code is shown below.
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.artifexdigital.android.listviewdemo3.MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="doClick"
android:text="Submit selection" />
</LinearLayout>
The activity is implemented with the java code is given below:
listView1 = (ListView) findViewById(R.id.listView1);
String[] someColors = new String[] { "Red", "Orange", "Yellow",
"Green", "Blue", "Indigo", "Violet", "Black", "White"};
ArrayList<String> colorArrayList = new ArrayList<String>();
colorArrayList.addAll( Arrays.asList(someColors) );
listAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked,
colorArrayList);
listView1.setAdapter( listAdapter1 );
listView1.setChoiceMode(listView1.CHOICE_MODE_MULTIPLE);
The usage pattern for the GridView is to define the grid in the XML layout is shown below
<GridView
android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:gravity="center" />
java Implementation of the GridView is shown below
gridView1 = (GridView) findViewById(R.id.gridView1);
creating a Gridview reference of type GridView class
String[] someColors = new String[] { "Red", "Orange", "Yellow",
"Green", "Blue", "Indigo", "Violet", "Black", "White"};
creating an String array to store the data for the adapter which is to be displayed in
the GridView
ArrayList<String> colorArrayList = new ArrayList<String>();
creating a ListArray to store a String Array of Values/data
colorArrayList.addAll( Arrays.asList(someColors) );
add new elements into the ArrayList via the add() method or a Collection via
the addAll() method. Here we need to add a collection of data via addAll() method.
listAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, colorArrayList);
creating ArrayAdapter which containd the default layout and array of data
gridView1.setAdapter( listAdapter1 );
Linking the adapter with the adapter view(GridView) using the setAdapter method
The adapterArray used by the grid is a ListArray. Lists are generally one-dimensional, whereas
grids are two-dimensional. We can conclude, then, that the grid actually displays list-oriented
data. And it turns out that the list is displayed by rows. That is, the list goes across the first row,
then across the second row, and so on.
<Spinner
android:id="@+id/spinner" android:prompt="@string/spinnerprompt"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
The purpose of the spinner is to allow the user to choose from a set of predetermined values:
when the user clicks the small arrow, a list is displayed, and the user is expected to pick a new
value. Populating this list is done in the same way as the other list controls: with an adapter.
The new attribute called android:prompt for setting a prompt(a hint about what to select. Eg:
select year) at the top of the list to choose from.
Because a spinner is often used like a drop-down menu, it is common to see the adapter get the
list choices from a resource file. An example that sets up a spinner using a resource file
is shown below.
One of the differences from our earlier list controls is that weve got an extra layout to contend
with when working with a spinner. The left side of Figure shows the normal mode of a spinner,
where the current selection is shown. In this case, the current selection is Saturn. Next to the
word is a downward-pointing arrow indicating that this control is a spinner and can be used to
pop up a list to select a different value. The first layout, supplied as a parameter to the
ArrayAdapter.createFromResource() method, defines how the spinner looks in normal mode. On
the right side of Figure, we show the spinner in the pop-up list mode, waiting for the user to
choose a new value. The layout for this list is set using the setDropDownViewResource()
method.
Understanding LayoutManagers:
Layout Managers are 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. For example, the LinearLayout class lays
out its children either horizontally or vertically, one after the other. All layout managers derive
from the View class, therefore you can nest layout managers inside of one another.
Table 5-1. Android Layout Managers
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
The LinearLayout Layout Manager
The LinearLayout layout manager is the most basic. This layout manager organizes its children
either horizontally or vertically based on the value of the orientation property.
LINEAR LAYOUT
LinearLayout with a Horizontal Configuration using XML
<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-->
</LinearLayout>
You can create a vertically oriented LinearLayout by setting the value of orientation to
vertical.
Understanding Weight and Gravity
Another important properties that can affect size and position of child controls are
weight and gravity.
We can use the weight attribute to allocate a portion of the layouts space to a view,
depending on its weight.
You can set a weight attribute using a float value for any view that you use in a
LinearLayout. Android will then divide the available space up amongst the views
proportionately, depending on their weight values.
You use weight to assign size importance to a control relative to the other controls in the
container. Suppose a container has three controls: one has a weight of 1, whereas the
others have a weight of 0. In this case, the control whose weight equals 1 will consume
the empty space in the container.
Gravity is the alignment of the views included in a Container.
if you want to align a labels text to the right, you would set its gravity to right. There are
quite a few possible values for gravity, including left, center, right, top, bottom,
center_vertical, clip_horizontal, and others.
android:gravit
y
This specifies how an object should position its content, on both the X
and Y axes. Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.
android:layout_height="fill_parent">
<EditText android:layout_width="wrap_content" android:gravity="center"
android:layout_height="wrap_content" android:text="one"
android:layout_gravity="right"/>
</LinearLayout>
Here the text is centered in the EditText, and which is aligned to the right of the LinearLayout.
As shown, the UI looks like a simple login form. The username label is pinned to the top
of the container, because we set android:layout_alignParentTop to true.
Similarly, the Username input field is positioned below the Username label because we
set android:layout_below. The Password label appears below the Username label, and
the Password input field appears below the Password label.
Besides these three layout attributes, you can also specify layout_above,
layout_toRightOf, layout_toLeftOf, layout_centerInParent, and several more.
Android also offers a layout manager that is mainly used to display a single item is called
FrameLayout.
You can, however, add multiple children to a FrameLayout and control their position
within the FrameLayout by assigning gravity to each child, using the
android:layout_gravity attribute.
FrameLayout, however, does not force you to have only one control visible at a time. If
you add many controls to the layout, FrameLayout will simply stack the controls, one on
top of the other, with the last one on top.
In Frame layout the controls are stacked, and that the top one is partially covering the
image behind it. The image which is large occupies the maximum size.
A style is a collection of properties that specify the style and format for view or window
A style can specify properties such as height, font color, font size, padding, background
color and much more.
Used to highlight or style a portion of the Views content either statically or dynamically
Statically, you can apply markup directly to the strings in your string
resources, as shown here:
<string name="styledText"><i>Static</i> style in a <b>TextView</b>.</string>
Note that you can use the following HTML tags with string resources: <i>, <b>, and <u>
for italics, bold, and underlined, respectively, as well as <sup> (superscript), <sub>
(subscript), <strike> (strikethrough), <big>, <small>, and <monospace>.
Styling a TextView controls content programmatically allows for much more flexibility
because you can style it at runtime. This flexibility can only be applied to a Spannable.
To get a TextView to store text as a Spannable, you can call setText() this way:
tv.setText("This text is stored in a Spannable", TextView.BufferType.SPANNABLE);
Then, when you call tv.getText(), youll get a Spannable.
EditText et =(EditText)this.findViewById(R.id.et);
et.setText("Styling the content of an EditText dynamically");
Using setText() method set the text which is to be displayed on the EditText
Spannable spn = (Spannable) et.getText();
Get the text displayed on the EditText using the method getText() and which is
stored in a spannable reference variable.
spn.setSpan(new BackgroundColorSpan(Color.RED), 0, 7,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sets the text styling to bold and italics and sets the background to red and which is
applied only to the characters from the position 0 to 7 using the
SPAN_EXCLUSIVE_EXCLUSIVE coding
A style is a collection of View attributes that is given a name so you can refer to that collection
by its name and assign that style by name to views.
Below code shows a resource XML file, saved in /res/values file
Defining a Style to Be Used Across Many 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>
</style>
</resources>
Using a Style in a View in Main_Activity.xml file
<TextView android:id="@+id/errorText"
style="@style/ErrorText"
android:text="No errors at this time"
/>
One really nice aspect of styles is that you can set up a hierarchy of them. We could define
a new style and base it on the style of ErrorText (Inheriting)
Defining a Style from a Parent Style
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ErrorText.Danger" >
<item name="android:textStyle">bold</item>
</style>
</resources>
This example shows that we can simply name our child style using the parent style as a prefix to
the new style name.
Therefore, ErrorText.Danger is a child of ErrorText and inherits the style attributes of the parent.
It then adds a new attribute for textStyle.
Android provides a large set of styles that we can use. To specify an Android-provided style, use
syntax like this:
style="@android:style/TextAppearance"
if you want to set the color of the text in your
TextView to a system style color, you could do the following:
<EditText android:id="@+id/et2"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textColor="?android:textColorSecondary"
android:text="@string/hello_world" />
The name of the textColor attribute value starts with the ? character instead of the @ character.
The ? character is used so Android knows to look for a style value in the current theme.
Themes
A theme is an android style applied to an entire activity or application rather than an individual
style.
To specify a theme for an activity or an application, add an attribute to the <activity> or
<application> tag in the AndroidManifest.xml file for your project. The code might look
like this:
<application android:theme="@style/MyApplicationTheme">
You can find the Android-provided themes in the same folder as the Android-provided styles,
with the themes in a file called themes.xml. When you look inside the themes file, you will see
a large set of styles defined, with names that start with Theme. Similarly like styles we can
extend themes like Theme.Dialog.AppError