Full recording of Android Application Development-How familiar are you with listview? Use getview to override inflate

Source: Internet
Author: User

Today, we will bring you some information about listview and adatper in "full process of Android Application Development. Including basic usage of listview and optimization of listview.

We often useProgramSo it is necessary to learn listview well. Listview is also a relatively difficult-to-use control in Android. This section details the usage of listview.

A listview usually has two responsibilities.

(1) Fill in the data to the layout.

(2) process user selection and click operations.

First, it is easy to understand that listview implements this function. The second point is not hard to achieve. Readers will find that this is very simple in their subsequent studies.

Creating a listview requires three elements.

(1) view of each column in listview.

(2) Fill in the View data or images.

(3) The adapter connecting data to listview.

That is to say, to use listview, you must first understand what an adapter is. An adapter is a bridge connecting data and adapterview (listview is a typical adapterview and will learn more later). It can effectively implement the separation setting between data and adapterview, makes it easier to bind adapterview to data and makes modification easier.

Many adapters are provided in Android. Table 4-5 lists the commonly used adapters.

Table 4-5 common adapters

Adapter

Description

Arrayadapter <t>

It is used to bind an array and supports generic operations.

Simpleadapter

Data used to bind the control defined in XML

Simplecursoradapter

Used to bind cursor data

Baseadapter

Common basic adapters

 

In fact, there are many more adapters. Note that various adapters only have different conversion methods and capabilities. Next we will bind data to listview by using different adapters (simplecursoradapter will not talk about it for the moment, which will be introduced later in SQLite ).

4.12.1 use arrayadapter for listview

Arrayadapter can be used to bind simple listview data. By default, arrayadapter binds the tostring value of each object to the pre-defined textview control in layout. Arrayadapter is easy to use.

Instance:

Project Directory: 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>

Copy code

Then initialize in activity.

Publicclass mylistview extends activity {

Privatestaticfinal string [] STRs = new string [] {
"First", "second", "third", "fourth", "th"
}; // Define a string array to display the listview content
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 the reference of the listview object
/* Set the adapter for listview to bind data */
LV. setadapter (New arrayadapter <string> (this,
Android. R. layout. simple_list_item_1, STRs ));

}
}

Copy code

 

▲Figure 4-29 running effect of listview using arrayadapter

CodeVery simple, as shown in Figure 4-29.

 

Analyze the steps used.

(1) define an array to store the items in the listview.

(2) create an arrayadapter object by implementing the arrayadapter constructor.

(3) bind arrayadapter through the setadapter () method of listview.

In step 2, it is necessary to mention that arrayadapter has multiple constructor functions. In this example, the most commonly used constructor is implemented. The first parameter is the context, and the second parameter is a layout resource ID containing textview, which is used to fill each row of listview. The third parameter is the content of listview. The second parameter can be used to customize a layout, but the layout must have a textview control. We usually use the resources provided by Android. In addition to the resources used in this example, there are also the following commonly used resources to implement listview with radiobutton and checkbox.

(1) specify the resource Android. R. layout. simple_list_item_checked to implement the listview with a selection box. You need to use the setchoicemode () method to set whether to select multiple or single choice. Otherwise, the selection effect cannot be achieved, as shown in Figure 4-30.

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 );

Copy code

(2) specify the resource Android. R. layout. simple_list_item_multiple_choice to implement the listview with checkbox. Similarly, you must use the setchoicemode () method to set one or more options. The running effect is 4-31.

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 );

Copy code

(3) specify the resource Android. R. layout. simple_list_item_single_choice to implement the listview with radiobutton. Note that a single choice is not specified here. You must use the setchoicemode () method to specify the multiple-choice or single-choice options. The running effect is 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 );

Copy code

 

 

▲< span> figure 4-30 select box listview ▲ figure 4-31 band checkbox listview ▲ / span> figure 4-32 band radiobutton listview

 

As mentioned above, listview also processes user operations in addition to data filling. You can bind a click listener to the listview using the following code. After clicking the listener, the number of lines clicked is displayed in the title bar.

LV. setonitemclicklistener (New onitemclicklistener (){

@ Override
Publicvoid onitemclick (adapterview <?> Arg0, view arg1, int arg2,
Long arg3 ){
// The row number is displayed on the title after clicking
Settitle ("the number you clicked" + arg2 + "line ");
}
});

Copy code

 

4.12.2 use simpleadapter for listview

Most of the time, you need to display something other than text in the list, such as slice. At this time, simpleadapter can be used. Simpleadapter is also very simple to use, and its functions are also very powerful. You can use it to customize the content of items in the listview, such as slice and multi-choice box. Let's look at an example to implement a listview with an imageview and textview for each row. Take a look at the running effect, as shown in Figure 4-34.

 

 

▲Figure4-34With iconsListview

 

First, add a listview control to the layout file.

You also need to define the layout of each row in a listview, and use relativelayout to implement a layout with two lines of words and an image.

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>

Copy code

After configuration, You can bind data to 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 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 an image
Map. Put ("itemtitle", "th" + I + "row ");
Map. Put ("itemtext", "this is the" + I + "row ");
Listitem. Add (MAP );
}

Simpleadapter msimpleadapter = new simpleadapter (this, listitem, // data to be bound
R. layout. Item, // layout of each row
// The Key of the data source in the dynamic array corresponds to the view of the definition layout.
New String [] {"itemimage", "itemtitle", "itemtext "},
Newint [] {R. Id. itemimage, R. Id. itemtitle, R. Id. itemtext}
);

LV. setadapter (msimpleadapter); // bind an adapter to the listview

LV. setonitemclicklistener (New onitemclicklistener (){

@ Override
Publicvoid onitemclick (adapterview <?> Arg0, view arg1, int arg2,
Long arg3 ){
Settitle ("You have clicked the" + arg2 + "row"); // you can set the title bar to display the row you have clicked on.

}
});
}
}

Copy code

Data Using simpleadapter is generally a list consisting of hashmap. Each section of the list corresponds to each row of listview. Through the simpleadapter constructor, map the data of each key of hashmap to the corresponding control in the layout file. This layout file is generally defined according to your own needs. Sort out the steps for using simpleadapter.

(1) define the layout implemented by each row of the listview as needed.

(2) define a list composed of hashmap and store the data in key-value pairs.

(3) construct the simpleadapter object.

(4) bind the lsitview to simpleadapter.

4.12.3 Optimization of listview using baseadapter and listview

In the use of listview, you sometimes need to add buttons and other controls in it to implement separate operations. That is to say, the listview does not only display data, but also processes user operations, but controls in it need to gain the user's focus. You can try to use simpleadapter to add a button to the listview entry. You will find that the button can be added but cannot get the focus. The click operation is overwritten by the listview item. At this time, the most convenient way is to use the flexible adapter baseadapter.

 

 

▲Figure4-35 baseadapterParty in

To use baseadapter, you must write a class to inherit it, while baseadapter is an abstract class that inherits its methods. The flexibility of baseadapter lies in its many methods to be rewritten. Let's take a look at which methods are available. 4-35 shows the methods implemented by the speechlistadapter inherited from baseadapter. The most important method is the getview () method. What are the functions of these methods? We analyze the principle of listview to answer questions for readers.

 

When the system starts to draw the listview, The getcount () method is called first. The returned value is the length of the listview. Then the system calls the getview () method and draws each row of the listview one by one based on the length. That is to say, if getcount () returns 1, only one row is displayed. Getitem () and getitemid () are called when data in the adapter needs to be processed and obtained. How to Use getview? If there are 10000 rows of data, it will be drawn 10000 times? This will definitely consume a lot of resources and cause the listview to slide very slowly. What should we do? An example is provided to illustrate how to optimize the display of listview when using baseadapter. In this example, the imageview in the previous section is replaced with a button and the button click event is processed. The listview display is optimized.

 

The layout file is similar to the previous example. You can view the layout file in the project directory of the CD. Here, only the activity class is provided.

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); // bind the adapter to the listview
/* Add click events for listview */
LV. setonitemclicklistener (New onitemclicklistener (){

@ Override
Publicvoid onitemclick (adapterview <?> Arg0, view arg1, int arg2,
Long arg3 ){
Log. V ("mylistviewbase", "you clicked the listview entry" + arg2); // output information in logcat

}
});

}
/* Add a method for getting data for ease of use */
Private arraylist
Arraylist /* Add data to the dynamic array */
For (INT I = 0; I <30; I ++)
{
Hashmap <string, Object> map = new hashmap <string, Object> ();
Map. Put ("itemtitle", "th" + I + "row ");
Map. Put ("itemtext", "this is the" + I + "row ");
Listitem. Add (MAP );
}
Return listitem;

}
/*
* Create a class that inherits the baseadapter to bind the view to the data.
*/
PrivateClass myadapter extends baseadapter {

Private layoutinflater minflater; // obtain a layoutinfalter object to import the layout.

/* Constructor */
Public myadapter (context ){
This. minflater = layoutinflater. From (context );
}

@ Override
Publicint getcount (){

Return getdate (). Size (); // return the length of the array
}

@ Override
Public object getitem (INT position ){
Returnnull;
}

@ Override
Publiclong getitemid (INT position ){
Return 0;
}
/* Explain this method in detail in the book */
@ Override
Public View getview (finalint position, view convertview, viewgroup parent ){
Viewholder holder;
// Observe convertview scrolling with listview
Log. V ("mylistviewbase", "getview" + Position + "" + convertview );
If (convertview = NULL ){
Convertview = minflater. Inflate (R. layout. item,
Null );
Holder = new viewholder ();
/* Get the object of 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 (); // retrieve the viewholder object
}
/* Set the content displayed by textview, that is, the data we store in the dynamic array */
Holder. Title. settext (getdate (). Get (position). Get ("itemtitle"). tostring ());
Holder. Text. settext (getdate (). Get (position). Get ("itemtext"). tostring ());

/* Add a click event for the button */
Holder. bt. setonclicklistener (New onclicklistener (){

@ Override
Publicvoid onclick (view v ){
Log. V ("mylistviewbase", "you clicked the button" + position); // print the click information of the button.

}
});

Return convertview;
}

}
/* Store controls */
Publicfinalclass viewholder {
Public textview title;
Public textview text;
Public button Bt;
}
}

Copy code

The running effect is 4-36. Note that the button will snatch the focus of the listview, and the button must be set to no focus. The setting is very simple. You only need to add a line under the XML button Tag: Android: focusable = "false. Observe the information output after clicking logcat, as shown in Figure 4-37.

▲Figure4-36UseBaseadapterOfListvie

W

 ▲Figure4-37ClickListviewEntries andButtonOutput

The getview () method in the Code is not easy to understand. In fact, you can directly import the layout and set the display content of the control without the so-called convertview and viewholder. However, this means that the number of rows of data to be drawn is obviously not desirable. An optimization method is used here. In the code, add a line of log output convertview content to the getview () method. Scroll down the listview, as shown in Figure 4-38.

As shown in Figure 4-38, convertview is zero when the first screen of listview is displayed when the activity is started. When you scroll down the listview, the preceding entries become invisible, and new entries appear below. At this time, convertview is no longer empty, but creates a series of convertview values. When the screen is rolled down, it is found that 11th rows of containers are used to hold 22nd rows, and 12th rows of containers are used to hold 23rd rows. That is to say, convertview is equivalent to a cache and starts to 0. When an entry becomes invisible, it caches its data and the subsequent entries only need to update the data, this greatly saves the cost of system data.

You can continue optimization. Although the previously drawn view is reused, to obtain the control, you must use the findviewbyid method in the control container. If the container is very complex, it will obviously increase the overhead of system resources. In the above example, the concept of tag is introduced. Maybe not the best way, but it does make listview smoother. In the Code, when convertview is empty, use the settag () method to bind a viewholder object for each view to store the control. When convertview is not empty and you reuse the created view, use the gettag () method to obtain the bound viewholder object. This avoids layer-by-layer query of the findviewbyid control, instead, you can quickly locate the control.

▲Figure4-38ScrollListviewOutputConvertviewValue

To sum up, this section describes how to bind listview data with baseadapter. Because baseadapter is flexible, it is more difficult to use than other controls. At the same time, the problem of listview optimization is also worth studying. A smooth listview will bring a better user experience.

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.