"Go" Android app development full record-how familiar are you with the ListView? ---good.

Source: Internet
Author: User

Original URL: http://www.cnblogs.com/noTice520/archive/2011/12/05/2276379.html

Today brings you to the "Android app development full record" in the ListView and Adatper part. Including the basic use of the ListView, the optimization of the ListView and so on.

We often use lists in the application to show some content, so it is very necessary to learn the ListView well. The ListView is also a more difficult-to-use control in Android, and this section will explain the usage of the ListView in detail.

A ListView usually has two responsibilities.

(1) Fill the data into the layout.

(2) Handle the user's choice of clicks and other actions.

The 1th is well understood, and the ListView is the realization of this function. The 2nd is not difficult to do, in the back of the study readers will find that this is very simple.

The creation of a ListView requires 3 elements.

(1) View of each column in the ListView.

(2) Fill in the view data or pictures, etc.

(3) Connect the data with the ListView adapter.

That is, to use the ListView, first understand what the adapter is. The adapter is a bridge that connects data and Adapterview (a ListView is a typical Adapterview, and later learns the rest), enabling it to effectively separate the data from the Adapterview settings, Makes Adapterview and data binding easier and easier to modify

Android offers a lot of adapter, table 4-5 lists several common ones.

Table 4-5 Common adapters

Adapter

Meaning

Arrayadapter<t>

Used to bind an array that supports generic operations

Simpleadapter

Used to bind the data corresponding to the controls defined in the XML

Simplecursoradapter

The data used to bind the cursor

Baseadapter

General-Purpose Base Adapter

In fact, there are many adapters, it is important to note that all kinds of adapter is just the way of conversion and ability is not the same. This is done by using different adapter to bind the data to the ListView (Simplecursoradapter, which is described later in SQLite).

4.12.1 listview using arrayadapter

A simple ListView data binding can be implemented with Arrayadapter. By default, Arrayadapter binds the ToString value of each object to the pre-defined TextView control in layout. The use of Arrayadapter is very simple.

Instance:

Project Catalog:Ex_04_12

Add a ListView control to the layout file.

<?xmlversion= "1.0" encoding= "Utf-8"?>
<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
>
<!--Add a ListView control--
<listview
Android:id= "@+id/lv"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
/>
</LinearLayout>

It is then initialized in the activity.

Publicclass Mylistview extends Activity {

Privatestaticfinal string[] STRs = new string[] {
"First", "second", "third", "fourth", "fifth"
};//defines a string array to display the contents of the ListView
Private ListView LV;

/** called when the activity is first created. */
@Override
Publicvoid onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);

LV = (ListView) Findviewbyid (r.id.lv);//Get a reference to the ListView object
/* Set adapter for the ListView to bind the data */
Lv.setadapter (New arrayadapter<string> (This,
Android. R.layout.simple_list_item_1, STRs));

}
}

▲ Figure 4-29 ListView using arrayadapter Run effect

The code is very simple and runs as shown in effect 4-29.

Analyze the steps used.

(1) Define an array to hold the contents of the item in the ListView.

(2) Create a Arrayadapter object by implementing the Arrayadapter constructor.

(3) Bind arrayadapter through the Setadapter () method of the ListView.

In the second step, it is necessary to say that Arrayadapter has multiple constructors, the most common one implemented in the example. The first parameter is the context, and the second parameter is a layout resource ID that contains TextView, which fills each row of the ListView. The third parameter is the contents of the ListView. The second parameter can customize a layout, but the layout must have a TextView control. Usually we use the resources provided by Android, in addition to the examples used, the following are commonly used to implement a ListView with RadioButton and checkbox.

(1) by specifying Android. R.layout.simple_list_item_checked This resource, implement a ListView with a selection box. You need to use the Setchoicemode () method to set the selection to multiple selection or radio, otherwise you will not be able to achieve the selection effect, run effect 4-30 shown.

The implementation code is as follows:

Lv.setadapter (New arrayadapter<string> (This,
Android. r.layout.simple_list_item_checked, STRs));
Lv.setchoicemode (listview.choice_mode_multiple);

(2) by specifying Android. R.layout.simple_list_item_multiple_choice This resource to implement a ListView with a checkbox. Similarly, you need to use the Setchoicemode () method to set a single or multiple selection, run effect 4-31 is shown.

The implementation code is as follows:

Lv.setadapter (New arrayadapter<string> (This,
Android. R.layout.simple_list_item_multiple_choice, STRs));
Lv.setchoicemode (listview.choice_mode_multiple);

(3) by specifying Android. R.layout.simple_list_item_single_choice This resource to implement a ListView with RadioButton. It is important to note that there is not a single radio specified here. is multi-Select or single-selection to be specified by the Setchoicemode () method, as shown in the run effect 4-32.

The implementation code is as follows:

Lv.setadapter (Newarrayadapter<string> (This,

Android. R.layout.simple_list_item_single_choice,strs));

Lv.setchoicemode (Listview.choice_mode_single);

▲ Figure 4-30 listview▲ with selection box 4-31 ListView with checkbox ▲ Fig . 4-32 ListView with radiobutton

As mentioned earlier, the role of the ListView is to handle the user's actions in addition to populating the data. The following code can be used to bind a click Listener to the ListView, click on the title bar to display the number of rows clicked.

Lv.setonitemclicklistener (New Onitemclicklistener () {

@Override
Publicvoid Onitemclick (adapterview<?> arg0, View arg1, int arg2,
Long Arg3) {
Click on the title to display click on the first few lines
Settitle ("You clicked on the" +arg2+ "line");
}
});

4.12.2 listview using simpleadapter

There are a lot of times when you need to show something other than text in the list, such as tablets. You can use Simpleadapter at this time. The use of Simpleadapter is also very simple, and its functions are very powerful. It allows you to customize the contents of the item in the ListView, such as slices, multi-marquee, and so on. To see an example, implement a ListView that has a ImageView and textview in each row. Let's take a look at the running effect, as shown in 4-34.

▲ Figure 4-34 ListView with icons

First add a ListView control to the layout file.

You also need to define a layout for each row in the ListView, using Relativelayout to implement a layout with two lines of text and one picture.

Item.xml:

<?xmlversion= "1.0" encoding= "Utf-8"?>
<relativelayout
Xmlns:android= "Http://schemas.android.com/apk/res/android"
android:layout_height= "Fill_parent"
Android:layout_width= "Fill_parent" >
<imageview
Android:layout_alignparentright= "true"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:id= "@+id/itemimage"
/>
<textview
Android:id= "@+id/itemtitle"
android:layout_height= "Wrap_content"
Android:layout_width= "Fill_parent"
Android:textsize= "20SP"
/>
<textview
Android:id= "@+id/itemtext"
android:layout_height= "Wrap_content"
Android:layout_width= "Fill_parent"
android:layout_below= "@+id/itemtitle"
/>
</RelativeLayout>

Once configured, data can be bound to the ListView in Java code.

Publicclass Mylistviewsimple extends Activity {

Private ListView LV;

/** called when the activity is first created. */
@Override
Publicvoid onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);

LV = (ListView) Findviewbyid (r.id.lv);
/* Define a dynamic array */
arraylist/* Store the data in the array */
for (int i=0;i<10;i++)
{
hashmap<string, object> map = new hashmap<string, object> ();
Map.put ("Itemimage", r.drawable.icon);//Add a picture
Map.put ("Itemtitle", "section" +i+ "line");
Map.put ("Itemtext", "This is the first" +i+ "line");
Listitem.add (map);
}

Simpleadapter msimpleadapter = new Simpleadapter (this,listitem,//data that needs to be bound
r.layout.item,//the layout of each row
The key of the data source in the dynamic array corresponds to the view in which the layout is defined
New string[] {"Itemimage", "Itemtitle", "Itemtext"},
Newint[] {R.id.itemimage,r.id.itemtitle,r.id.itemtext}
);

Lv.setadapter (msimpleadapter);//For the ListView binding adapter

Lv.setonitemclicklistener (New Onitemclicklistener () {

@Override
Publicvoid Onitemclick (adapterview<?> arg0, View arg1, int arg2,
Long Arg3) {
Settitle ("You clicked on the" +arg2+ "line");//Set the title bar to display the clicked line

}
});
}
}

Data that uses Simpleadapter is typically a list of hashmap that each section of the list corresponds to each row of the ListView. The data for each key of HashMap is mapped to the corresponding control in the layout file through the Simpleadapter constructor. This layout file is usually defined by its own needs. Comb the steps to use Simpleadapter.

(1) Define the layout implemented by each row of the ListView as needed.

(2) Define a list of HashMap and store the data in the form of key-value pairs.

(3) constructs the Simpleadapter object.

(4) Bind the Lsitview to the Simpleadapter.

4.12.3 ListView using baseadapter and listview optimization

In the use of the ListView, sometimes it is necessary to add controls such as buttons inside, to achieve a separate operation. In other words, the ListView is no longer just a display of data, it is not just the line to handle the user's actions, but the controls inside to get the user's focus. Readers can try Simpleadapter Add a button to the ListView entry, will find that can be added, but do not have the focus, click action by the ListView item is overwritten. The most convenient way to do this is to use the flexible adapter Baseadapter.

▲ Figure 4-35 method in Baseadapter

Using Baseadapter must write a class to inherit it, while Baseadapter is an abstract class that inherits the way it must implement it. The flexibility of baseadapter is that it rewrites a lot of methods and looks at what methods are available, and 4-35 shows the method implemented by the Speechlistadapter inherited from Baseadapter, the most important of which is the GetView () method. How does all this work? We analyze the principle of the ListView to answer the reader.

When the system starts drawing the ListView, First call the GetCount () method. Gets its return value, which is the length of the ListView. The system then calls the GetView () method to draw each row of the ListView one at a length. That is, if you let GetCount () return 1, only one row is displayed. GetItem () and Getitemid () are called when the data in the adapter needs to be processed and obtained. So how does getview use it? If you have 10000 rows of data, draw 10,000 times? This is sure to consume a lot of resources, causing the ListView to slide very slowly, so what should be done? Use an example to illustrate how to optimize the display of the ListView when using Baseadapter. The example replaces the ImageView in the previous section with a button and handles the button's click event, which optimizes the display of the ListView.

The layout file is similar to the previous example, and the reader can be viewed in the project catalog of the disc, where only the activity class is given.

Publicclass Mylistviewbase extends Activity {

Private ListView LV;
/* Define a dynamic array */
Arraylist

/** called when the activity is first created. */
@Override
Publicvoid onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);

LV = (ListView) Findviewbyid (r.id.lv);
Myadapter madapter = new Myadapter (this);//Get a Myadapter object
Lv.setadapter (madapter);//For ListView binding Adapter
/* Add a Click event for the ListView */
Lv.setonitemclicklistener (New Onitemclicklistener () {

@Override
Publicvoid Onitemclick (adapterview<?> arg0, View arg1, int arg2,
Long Arg3) {
LOG.V ("Mylistviewbase", "You clicked on the ListView entry" + arg2);//output information in Logcat

}
});

}
/* Add a method to get the data, easy to use */
Private arraylist
arraylist/* Add data for dynamic arrays */
for (int i=0;i<30;i++)
{
hashmap<string, object> map = new hashmap<string, object> ();
Map.put ("Itemtitle", "section" +i+ "line");
Map.put ("Itemtext", "This is the first" +i+ "line");
Listitem.add (map);
}
return listItem;

}
/*
* Create a new class to inherit Baseadapter, to implement the view and data binding
*/
Privateclass Myadapter extends Baseadapter {

Private Layoutinflater minflater;//Get a Layoutinfalter object to import the layout

/* Constructor function */
Public Myadapter (Context context) {
This.minflater = Layoutinflater.from (context);
}

@Override
Publicint GetCount () {

Return GetDate (). Size ();//Returns the length of the array
}

@Override
Public Object getItem (int position) {
Returnnull;
}

@Override
Publiclong getitemid (int position) {
return 0;
}
/* Explain the method in detail in the book */
@Override
Public View GetView (finalint position, view Convertview, ViewGroup parent) {
Viewholder Holder;
Observe the Convertview with the ListView scrolling situation
LOG.V ("Mylistviewbase", "GetView" + position + "" + Convertview);
if (Convertview = = null) {
Convertview = Minflater.inflate (R.layout.item,
NULL);
Holder = new Viewholder ();
/* Get objects for each control */
Holder.title = (TextView) Convertview.findviewbyid (r.id.itemtitle);
Holder.text = (TextView) Convertview.findviewbyid (R.id.itemtext);
HOLDER.BT = (Button) Convertview.findviewbyid (R.id.itembutton);
Convertview.settag (holder);//Bind Viewholder Object
}
else{
Holder = (viewholder) convertview.gettag ();//Remove Viewholder Object
}
/* Set the contents of the TextView display, which is the data we hold in the dynamic array */
Holder.title.setText (GetDate (). get (position). Get ("Itemtitle"). toString ());
Holder.text.setText (GetDate (). get (position). Get ("Itemtext"). toString ());

/* Add Click events for button */
Holder.bt.setOnClickListener (New Onclicklistener () {

@Override
Publicvoid OnClick (View v) {
LOG.V ("Mylistviewbase", "You clicked the button" + position); Print click Information for a button

}
});

return convertview;
}

}
/* Store Controls */
Publicfinalclass viewholder{
Public TextView title;
public TextView text;
Public Button BT;
}
}

Run effect 4-36 as shown. Also note that the button robs the ListView of the focus and needs to set the button to have no focus. The setting is very simple, just add one line under the button tag of the XML: Android:focusable= "False" code is OK. After the Logcat observation, the output information is shown in 4-37.

▲ Figure 4-36 using Baseadapter's listvie

W

▲ Figure 4-37 Click on the output from the ListView Entry and button

The GetView () method in the code is not easy to understand. Instead of the so-called Convertview and Viewholder, you can simply import the layout and set what the control displays. But that means how many rows of data you need to draw the ListView, which is obviously undesirable. An optimized approach is used here. In the code, a line of log output Convertview is added to the GetView () method. Scroll the ListView, as shown in output information 4-38.

As can be seen from figure 4-38, when the activity is started to render the first screen listview, the Convertview is zero. When the user scrolls down the ListView, the entry above becomes invisible, and the new entry appears below. At this time Convertview is no longer empty, but instead creates a series of convertview values. When you scroll down one screen, you find that the container on line 11th is used to hold the 22nd row, and the container in line 12th is used to hold the 23rd row. In other words, Convertview is equivalent to a cache, starting at 0, when an entry becomes invisible, it caches its data, the subsequent entry only needs to update the data, which greatly saves the overhead of system data.

You can also continue to optimize. Although you have reused the view that you have drawn, you need to get the controls in it by Findviewbyid in the control's container. If this container is very complex, this obviously increases the overhead of system resources. In the above example, the concept of tag is introduced. It may not be the best approach, but it does make the ListView smoother. Code, when Convertview is empty, use the Settag () method to bind a Viewholder object that holds the control for each view. When Convertview is not empty, reusing a view that has already been created uses the Gettag () method to get the bound Viewholder object, which avoids the findviewbyid of a layer query on the control and quickly navigates to the control.

▲ Figure 4-38 scrolling The Convertview value of the ListView output

To summarize, this section describes the data that binds the ListView with Baseadapter. Because Baseadapter is very flexible, it is also more cumbersome to use than other controls. At the same time, the optimization problem of the ListView is also worthy of reader's study, a smooth listview will bring a better user experience.

"Go" Android app development full record-how familiar are you with the ListView? ---good.

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.