Pro Android learning notes (18): user interface and control (6): adapter and adapterview

Source: Internet
Author: User

Adapterview is not only the UI, but also the data associated to the UI. For example, listview is often used in mobile phones.

Listview, gridview, spinner, and gallery are both adapterviews. adapterview is a viewgroup, that is, a container. It contains multiple sub-views with the same UI layout. For adapterview, data is mapped to the subview through the adapter. An adapterview needs to describe the layout of the subview, and how the adapter maps data to one or more controls on each sub-view.

Simplecursoradapter

Simplecursoradapter is an implementation class of the adapter interface. We take listview as an example to analyze its structure.

The left part of the figure is the listview, which consists of sub-views with the same structure. The sub-views correspond to the same layout, which can be described by an XML file and contains one or more controls, in this example, place a textview control. Because the child view corresponds to the same layout, the resource ID of the control in each child view is the same, because the resource ID is specified by the same layout.

The right part of the figure is a data source, such as the content provider or SQLite database. A cursor is returned for a query. The adapter is the key to associating the listview on the left and the data source on the right. It reads a group of data from the data source and associates it with a corresponding subview, the specific data is displayed in the control of the Child view layout. Reference: an adapter object acts as a bridge betweenAdapterView
And the underlying data for that view.

Next, we will use a simple example to further illustrate. The name of the mobile phone contact is displayed on a listactivity. Android listactivity. Its Layout contains only one full-screen listview. If we want to use our own layout and listactivity, the ID of the listview set in layout must be Android: id = "Android: ID/List ". In this example, we use the default layout of listactivity.

Public class uiadapterdemo extendsListactivity{// The listactivity that the listview needs to integrate into the system
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
// Read the contact information to cursor. This is a table structure. Each contact has multiple details.
Cursorloader = new cursorloader (getapplicationcontext (),
Contactscontract. Contacts. content_uri,
Null, null, null, contactscontract. Contacts. display_name + "ASC ");
Cursor c = cursorloader. loadinbackground ();

// In this example, we only need to display the displayname in the contact to the textview control in the subview. The from and to records the mappings respectively. Note that this is a one-to-one correspondence between data items and controls.
String [] From = {contactscontract. Contacts. display_name };
Int [] to = {Android. R. Id. text1 };
Simplecursoradapter adapter = new simplecursoradapter (this,
/* Context */
Android. R. layout. simple_list_item_1,
/* Childlayout ID: Layout ID of the sub-view. Here we use a simple layout implemented by the system, which contains only one textview and the ID is Android. r. id. text1, which explains why we need to enter this value in */
C,/* Data source: cursor */
From,
/* Selected data items in the data source. In this example, the contact has many data items. We only select displayname */
To, /* Controls corresponding to these data items */
Cursoradapter. flag_register_content_observer );
/* Flag. From the reference, this value is not recommended currently. When the notification arrives (such as data changes), oncontentchanged ()*/

This.Setlistadapter(Adapter);/* apply the adapter to the listactivity listview */
}

In this example, to read the contact list, you must declare the permission in androidmanifest. xml:

<Uses-Permission Android: Name = "android. Permission. read_contacts"/>

Listview does not care about the rendering in the sub-view, but organizes the sub-view. Listview, gridview, spinner, and gallery under adapterview are different sub-view organization methods. Listview is a row-by-row display method. When listview wants to display a row of child views, it calls getview () and getview () of the adapter () specifically, the from column data of a row of the data source is displayed in the Child View Control of the row. If we want to use our own layout, we may need to overwrite this method. If the screen shows only 10 rows, in principle, listview only needs to get the sub-view of the 10 rows, instead of getting hundreds of rows, but the system actually gets more, so that when the fingers move quickly, you can see the new line display more quickly.

Note: listview is used as an example here, but other types of adapterview can also be used in general mode.

System preset Layout

In this example, chreceivlayout ID starts with Android. R., which indicates that it is a system preset, rather than the resources in our local/Res. We canSDK/plateforms/<Android-version>/data/RES/LayoutSee the predefined layout. The simple_list_item_1.xml file is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>
<! -- ...... -->
<Textview xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Id = "@ Android: ID/text1" <! -- ID of the corresponding control: Android. R. Id. text1 -->
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: textappearance = "? Android: ATTR/textappearancelistitemsmall"
Android: gravity = "center_vertical"
Android: paddingstart = "? Android: ATTR/listpreferreditempaddingstart"
Android: paddingend = "? Android: ATTR/listpreferreditempaddingend"
Android: minheight = "? Android: ATTR/listpreferreditemheightsmall"
/>

Arrayadapter

Cursor is a two-dimensional table data source. The simpler case is the one-dimensional string [], which corresponds directly to the unique textview in the sub-view. In this case, the simplest arrayadapter can be used, as shown below. Compared with simplecursoradapter, because it is a one-dimensional model, the from and to operations are not required.

Arrayadapter <string> adapter = newArrayadapter <string>(This,
/* Context */

Android. R. layout. simple_list_item_1,/* Childlayout ID: Layout ID of the subview */
New String [] {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune "});/* Data source: String [] */
This. setlistadapter (adapter );

The data source can be from the string-array of the resource. It is defined in the XML file under/RES/values.

<String-array name = "planets">
<Item> mercury </item>
<Item> Venus </item>
<Item> Earth </item>
<Item> Mars </item>
<Item> Jupiter </item>
<Item> Saturn </item>
<Item> Uranus </item>
<Item> Neptune </item>
</String-array>

You can use either of the following methods:

Arrayadapter <string> adapter = new arrayadapter <string> (this,
Android. R. layout. simple_list_item_1,
Getresources (). getstringarray (R. array. Planets));

Arrayadapter <charsequence> adapter =Arrayadapter. createfromresource(This,
R. array. Planets, Android. R. layout. simple_list_item_1 );

Dynamic Data addition, insertion, deletion, and sorting

Arrayadapter can dynamically change data by using Add (), insert (), remove (), and sort (). However, if we perform adpater. Add ("Pluto") in the preceding example, the system reports java. Lang. nullpointerexception. The premise for dynamic adjustment is that the data source is scalable, that is, the size can be adjusted. In the preceding example, the data source is actually string [8]. We need to change some Code as follows:

List <string> planents= New arraylist <string> ();
// Use the Scalable Data Format of arraylist as the so-called Data Source
Initplanets (planets); // initialize the list data source.
Adapter = new arrayadapter <string> (this, Android. R. layout. simple_list_item_1, planents );
This. setlistadapter (adapter );
......
......
Adapter.Add("Pulto ");
Adapter.Notifydatasetchanged(); // In a small example, this statement can take effect without being added, but we recommend that you add it to ensure synchronization.

Custom textview Style

Arrayadapter has multiple constructors. Instead of using system presets, we use custom textviews. For example, we can set in/RES/layout/ui_my_textview.xml:

<? XML version = "1.0" encoding = "UTF-8"?>
<Textview xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: textcolor = "#005555"
Android: Id = "@ + ID/my_textview"
Android: layout_width = "wrap_content"
Android: layout_height = "match_parent">
</Textview>

The related code is as follows:

Arrayadapter <string> adapter = new arrayadapter <string> (this,
R. layout. ui_my_textview,/* Layout of the sub-view, which is set by ourselves in the resource */
R. Id. my_textview,/* Control ID of the textview in which data is to be filled */
Getresources (). getstringarray (R. array. Planets ));

In addition, we can also embed adapterview in layout, such as listview lv; LV. setadapter (adapter );

Other adapters

Arrayadapter: The layout of the sub-view contains only one textview. In textview, enter the value of object. tostring () in array. We can rewrite tostring () to perform the required processing. If it is not textview, You need to override the getview (INT, view, viewgroup) function and return the view.

Cursoradapter: Associate cursor data with listview. The cursor must contain "_ id", and the basecolumns interface of the database SQLite already has this value.

Simpleadapter: Used for static data, such as data from resource.

Resourcecursoradapter: It is an extension of cursoradapter. You can specify XML resources to create various sub-views.

Simplecursoradapter: It is an extension of cursoradapter. You can map the data of cursor to textview or imageview in the subview.

We will use them in later learning.

Related links:
My android development articles

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.