"Turn" Pro Android Learning Note (18): User interface and Control (6): Adapter and Adapterview

Source: Internet
Author: User

Directory (?) [-]

    1. Simplecursoradapter
      1. Layout of the system presets
    2. Arrayadapter
      1. Dynamic Data interpolation and deletion sorting
      2. Custom TextView Style
    3. Other Adapter

Adapterview is not just a UI, but it also associates data to the UI, such as a ListView that is often used in a phone adapterview.

The ListView, GridView, spinner, and gallery are all Adapterview,adapterview viewgroup, which is the container that contains the same sub-view with multiple UI layouts. For Adapterview, mapping data to child view through adapter, a Adapterview needs to describe the layout of the child view and adapter how to map the data to 1 or more controls on each child view.

Simplecursoradapter

Simplecursoradapter is an implementation class of the adapter interface, we use the ListView as an example to analyze its structure concretely.

The left part of the graph, which is a ListView, consists of a sub-view of the same structure, which corresponds to the same layout, which can be described by an XML file, in which one or more controls are placed, and in this case, a TextView control is placed. Because the child view corresponds to the same layout, the resource ID of the control inside each child view is the same because the resource ID is specified by the same layout.

The right part of the graph is a data source, such as a content provider or SQLite database, and the query returns a cursor. Adapter is the key to associating the left-hand listview with the right-side data source, which reads a set of data from the data source, correlates it to a corresponding child view, and renders the specific data in the controls in that child view layout. The reference reads: An Adapter object acts as a bridge between an and the AdapterView underlying data for that view.

Below, let's take a simple example to further illustrate. We display the name of the phone contact on a listactivity. Android Listactivity, its layout contains only a full-screen listview, if we want to use our own layout, there is the use of listactivity, Then the ID of the ListView set in our layout must be Android:id= "Android:id/list". In this example, we use the listactivity default layout.

public class Uiadapterdemo extendslistactivity{//listview requires an integrated system listactivity
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Reads the contact information into the cursor, which is a tabular structure with multiple details for each contact.
Cursorloader Cursorloader = new Cursorloader (Getapplicationcontext (),
ContactsContract.Contacts.CONTENT_URI,
NULL, NULL, NULL, ContactsContract.Contacts.DISPLAY_NAME + "ASC");
Cursor C = Cursorloader.loadinbackground ();

//In this example, we simply display the DisplayName in the contact, corresponding to the TextView control in the child view. The From and to records correspond to each other. Note that this is the one by one correspondence of the data item and the control.
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: The ID of the layout of the child view, here we choose a simple layout that the system has implemented, it only a textview,id for Android . R.id.text1, this explains why we have to fill this value in to. */
C,/* Data source: cursor*/
From,
/* Data item selected in the data source, in this case the contact has a lot of data items, we only select displayname*/
to,/ * The corresponding control for these data items * /
cursoradapter.flag_register_content_observer); /* flag, from reference, this value is not currently recommended when a notification arrives (e.g. data changes), triggering oncontentchanged () */
This.Setlistadapter(adapter);/* Adapter applies to listactivity listview*/
}

This example reads the contact list and requires a permission declaration in Androidmanifest.xml:

<uses-permission android:name= "Android.permission.READ_CONTACTS"/>

The ListView does not specifically care about rendering within a child view, but instead organizes the child view. Adapterview the following ListView, GridView, Spinner, gallery are different sub-view organization methods. The ListView is a horizontal line of rendering, and when the ListView is about to display a row of sub-view, call adapter's GetView (), GetView () to display the From column data of a row from the data source in the control of that row's child view. If we want to use the layout of our own design, we may need to overwrite the method. If the screen displays only 10 rows, the ListView simply fetches the 10 rows of sub-view and does not need to fetch the hundreds of rows, but in fact the system gets more, with the intention of quickly moving the finger to see the new line display faster.

Note that we use the ListView here as an example, but the generic way can also be used with other types of adapterview.

Layout of the system presets

In the example, the Chlidlayout ID starts with ANDROID.R., which is represented as a system preset, not a resource within our local/res. We can see these preset layouts in the sdk/plateforms/<android-version>/data/res/layout . Where 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" <!--the corresponding control id: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

The cursor is a two-dimensional tabular data source, and a simpler case is one-dimensional string[], which corresponds directly to the only textview in the child view, which can be used with the simplest arrayadapter, as shown below. Compared with Simplecursoradapter, because it is a one-dimensional, it does not require from and to correspondence.

arrayadapter<string> adapter = new arrayadapter<string> (this,/ * context * /
Android. R.layout.simple_list_item_1, /* childlayout ID: Layout ID of Child view */
New string[]{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}); /* Data Source: string[]*/
This.setlistadapter (adapter);

The data source can come from a resource's string-array. 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>

This can be done in two ways:

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 increase, interpolation, deletion, sorting

Arrayadapter can make dynamic Data changes using Add (), insert (), remove (), sort (). But if we do Adpater.add ("Pluto") in the example above, the system will report java.lang.NullPointerException. The prerequisite for dynamic adjustment is that the data source is scalable, that is, the size can be adjusted, and the above example, the data source is actually string[8]. We need to change some code as follows:

list<string> planents = new arraylist<string> (); //Using ArrayList's scalable data format so-called data sources
Initplanets (planets); Initialize the list's data source settings
adapter= New Arrayadapter<string> (this, Android. R.layout.simple_list_item_1, planents);
This.setlistadapter (adapter);
......
......
Adapter. Add ("Pulto");
Adapter. notifydatasetchanged (); In small cases, it is not necessary to add this sentence, but it is recommended to add it to ensure synchronization

Custom TextView Style

Arrayadapter has multiple constructors. Instead of using the system presets, we use the textview of our own definition style. For example, we set up 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 relevant code is as follows:

arrayadapter<string> adapter = new Arrayadapter<string> (This,
R.layout.ui_my_textview,/ * Layout of Child view, set by us in the resource */
R.id.my_textview,/ * TextView control to populate the data in child view id*/
Getresources (). Getstringarray (r.array.planets));

In addition, we can embed adapterview in layout, such as the ListView LV; Lv.setadapter (adapter);

Other Adapter

Arrayadapter: It is considered that the layout of the sub-view contains only a single textview. TextView will fill in the value of object.tostring () in the array. We can do the required processing by overriding ToString (). If it is not textview, you need to rewrite the GetView (Int,view, ViewGroup) function and return to View.

cursoradapter: Used to associate cursor data with a ListView. Where the cursor must have a "_id" entry, the database SQLite Basecolumns interface already has this value.

simpleadapter: Typically used for static data, such as data from resource.

Resourcecursoradapter: is an extension of cursoradapter that can create individual child view by specifying the XML resource.

Simplecursoradapter: is an extension of cursoradapter that maps the cursor's data to TextView or ImageView in the child view.

We will use them in later studies.

RELATED Links: My Android development related articles

"Turn" Pro Android Learning Note (18): User interface and Control (6): Adapter and Adapterview

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.