qianfeng-android-day08-Basic Learning: the ListView

Source: Internet
Author: User

ListView First, ListView Introduction: (a), ListView Concept:

The ListView is one of the most important components of Android, with a ListView in almost every Android app. It lists the list items that you want in a vertical list.

Java.lang.Object

? Android.view.View

? Android.view.ViewGroup

? Android.widget.adapterview<t extends Android.widget.adapter>

? Android.widget.AbsListView

? Android.widget.ListView

"Remarks:"

Java.lang.Object

? Android.view.View

? Android.view.ViewGroup

? Android.widget.adapterview<t extends Android.widget.adapter>

? Android.widget.AbsSpinner

? Android.widget.Spinner

(ii), two responsibilities of the ListView:

Populate the layout with the data;

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

(iii), the display of a list requires three elements:

1. LISTVEIW: A view used to display a list;

2. Adapter: An intermediary used to map data to a ListView;

3. Data source: The specific string, picture, or base component that will be mapped.

(iv), what is an adapter?

the adapter is a connection data and Adapterview Bridge, through it can effectively achieve the separation of data and adapterview settings, so that the adapterview and data binding more convenient and easy to modify. The common adapters for adapting data source data to a ListView are: Arrayadapter, Simpleadapter.

Arrayadapter is the simplest, can only display a line of words;

Simpleadapter has the best extensibility, can customize a variety of layouts, in addition to text, you can also put ImageView (picture), button (buttons), CheckBox (check box) and so on;

however, in practical work, custom adapters are commonly used. the custom adapter class that inherits from Baseadapter.

(v), common UI Properties for the ListView:

Android:divider

Android:dividerheight

Third, create ListView: (a), Arrayadapter Implementing Single-Line text listview: (No custom layout required, using system-provided layouts)

1, the use of steps.

(1), define an array to hold the contents of the item in the ListView;

(2) to create a Arrayadapter object by implementing Arrayadapter construction method;

(3), bind arrayadapter through the Setadapter () method of the ListView.

"Remarks:"

Arrayadapter has multiple construction methods, the one that most commonly uses three parameters.

First parameter: Context object;

a second parameter: The layout resource ID of each row (that is, item) of the ListView;

A third parameter: The data source for the ListView.

2, using the system to bring the different effects of the layout file:

A, Android. R.layout.simple_list_item_1:

B, Android. R.layout.simple_list_item_checked

C, Android. R.layout.simple_list_item_multiple_choice

D, Android. R.layout.simple_list_item_single_choice

3. Core code:

names = new arraylist<string> ();

for (int i = 0; i <; i++) {

Names.add ("Zhang San:" + i);

}

adapter = new Arrayadapter<string> (this, Android. R.layout.simple_list_item_1, names);

" Special Remarks:" The difference between a ListView listener and a spinner listener: "Focus"

Spinner is: Setonitemselectedlistener

The ListView is: Setonitemclicklistener

can the two listeners be used interchangeably?

in the Using Onitemclicklistener in Spinner is an exception. Java.lang.RuntimeException:setOnItemClickListener cannot is used with a spinner. If Onitemselectedlistener is used in the ListView, there is no response, i.e. the listener is not triggered to execute;

Parent.getselecteditem () and parent.getitematposition (position) can return object objects in the callback method of the Onitemselectedlistener listener. In the callback method of the Onitemclicklistener Listener, Parent.getselecteditem () can only return null.

(ii), Simpleadapter implementing Multi-line text listview: Customizing the Item layout file)

1, the use of steps.

(1), define a collection to hold the contents of the item in the ListView;

(2), define a layout file for item;

(3), create a Simpleadapter object;

(3), bind simpleadapter through the Setadapter () method of the ListView.

2. Core code:

(iii), Simpleadapter implements multiple lines of text with pictures in the ListView:

1, the use of steps.

(1), define a collection to hold the contents of the item in the ListView;

(2), define a layout file for item;

(3), create a Simpleadapter object;

(4), bind simpleadapter through the Setadapter () method of the ListView.

2. Core code:

public class Mainactivity extends Activity {

Private list<map<string, object>> data;

Private int[] images;

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_main);

InitData ();

ListView LV = (ListView) Findviewbyid (r.id.lv);

First parameter context

The second parameter represents a data source

The third parameter represents the resource ID of each item's layout

The fourth parameter represents a key in the map

The fifth parameter represents the ID of the control in the item layout, corresponding to key one by one in the map

Simpleadapter adapter = new Simpleadapter (this, data, R.layout.listview_item,

New string[] {"Image", "name", "Phonenum"}, new int[] {r.id.iv, R.ID.NAME_TV, R.ID.PHONE_TV});

Lv.setadapter (adapter);

}

private void InitData () {

Images = new int[] {r.drawable.a0, r.drawable.a1, R.drawable.a2, r.drawable.a3, r.drawable.a4, R.drawable.a5,

R.drawable.a6, R.drawable.a7, R.drawable.a8, r.drawable.a9, r.drawable.a10, R.DRAWABLE.A11,

R.drawable.a12, R.drawable.a13, R.drawable.a14, R.drawable.a15, R.drawable.a16, R.drawable.a17,

R.drawable.a18, R.drawable.a19, R.drawable.a20, R.drawable.a21, R.drawable.a22, R.drawable.a23,

R.drawable.a24, R.drawable.a25, R.drawable.a26, R.drawable.a27, R.drawable.a28, R.drawable.a29,

R.drawable.a30, R.drawable.a31, R.drawable.a32, R.drawable.a33, R.drawable.a34, R.drawable.a35,

R.drawable.a36, R.drawable.a37, R.drawable.a38, R.drawable.a39, R.drawable.a40, R.drawable.a41,

R.DRAWABLE.A42};

data = new arraylist<map<string, object>> ();

for (int i = 0; i < images.length; i++) {

map<string, object> map = new hashmap<string, object> ();

Map.put ("image", images[i]);

Map.put ("name", "John Doe:" + i);

Map.put ("Phonenum", "1856555----" + i);

Data.add (map);

}

}

}

(iv), Baseadapter Custom Adapter Implementation ListView:

1, the use of steps.

(1), define a collection to hold the contents of the item in the ListView;

(2), define a layout file for item;

(3), defines a subclass Myadapter that inherits Baseadapter, overrides the non-implemented method, (defines Viewholder, overrides the GetView () method)

(4), create an internal class: Myadapter extends Baseadapter;

implementation of non-implemented methods:GetCount (), GetItem (), Getitemid (), GetView ();

Defining inner Classes Viewholder, the controls in the item layout file are defined as attributes;

To build a layout shim object: Layoutinflater.from (context);

Call the Inflate () method of the layout filler object to populate the item layout file, assigning the returned view object to Convertview;

Call the Findviewbyid () of the Convertview object to get the control in the item layout, assign the control object to the property in Viewholder;

Set the label for the Convertview object, that is, call the Settag () method, and attach the Viewholder object as a label on the Convertview object;

Retrieves the Viewholder object from the Convertview object from a label based on Convertview.

(3), bind the custom Myadapter object through the Setadapter () method of the ListView.

2. Core code:

(v), Convertview principle:

The adapter function is a bridge between the ListView interface and the data, and when each item in the list is displayed to the page, the adapter GetView method is called to return a view.

What if there are thousands of items in our list? Does it take up a lot of system resources?

There is a widget called Recycler in Android, and if you have 100 item, only visible items exist in memory, others in recycler.

The ListView requests a type1 view (GetView) First, and then requests that the other visible item,convertview be empty (null) in GetView.

when item1 rolls out of the screen, and a new item comes up from the bottom of the screen, the ListView requests a type1 view, Convertview is not a null value at this time, and its value is item1. You just need to set up the new data and then return to Convertview without recreating a view.

Iv. What is ListView Click on the Supernatural event? "Important" (a), description of the phenomenon:

in the project The ListView is more than just simple text, it often needs to define the ListView itself, and if there are child controls such as Imagebutton,button,checkbox in the item you define, these child controls will get the focus, So when you click on the child control in item there is a change, and the item itself is not responding with a click.

the key to the solution is:android:descendantfocusability

Defines the relationship between the ViewGroup and its descendants when looking-a View to take focus.

Defines the relationship between ViewGroup and its child controls when a view acquires focus.

There are three types of values for the property:

Beforedescendants:viewgroup takes precedence over its subclass control and gets to focus

Afterdescendants:viewgroup gets focus only if its subclass control does not need to get focus

Blocksdescendants:viewgroup overrides the subclass control and gets the focus directly

usually we use a third kind, that is, in The root layout of the item layout plus android:descendantfocusability= "Blocksdescendants"

blocking child controls from grabbing the focus, allowing Item has focus. So that the Onitemclick of the ListView can be triggered correctly, and the item on the button and other controls in the Click can also trigger their own Click event, then the ListView click on the supernatural event is over.

You can also set android:focusable= "false" on all the controls in the item that have preemption focus.

ListView Optimization Tips

first, the previous section review:

(i) fully understand the role of Convertview:

1, mobile phone program after the operation:

2, just after the Logcat record:

3, the screen after the effect of sliding:

4, the screen after sliding logcat record:

"Description:" The phone screen shows 10 data at a time, so the first time you load, a new 10 Viewholder object is created. The IDs of these 10 objects can be seen from: @411e8a18, @413ab880, and so on.

when the screen slides, some item slides out of the screen, and a new item enters the screen from the bottom. You can see that the new item enters the screen with only one new Viewholder, and the others are reused Convertview.

Second, detail Issues in ListView optimization:

1. Android:layout_height Properties:

must be The layout Height property of the ListView is set to non-wrap_content (which can be absolute values such as MATCH_PARENT/FILL_PARENT/400DP), if the ListView has a layout height of "wrap_content", Then GetView () is called repeatedly. In general, an item will be called about three times.

2, Viewholder:

Use Viewholder the inner class, define the control that needs to be shown in the item layout file as a property (in fact Viewholder is a custom model class). This makes it possible to synthesize a whole number of controls scattered in the item, which effectively avoids image dislocation.

3, Convertview:

The ListView load is an item loaded with an item, so that it inflate an item layout every time, and then Findviewbyid all the controls on that layout again. When the amount of data is large, it is unthinkable. And the use of recycle recycling can solve the problem. So be good at reusing Convertview, this can reduce the process of filling layout, reduce the number of Viewholder object instantiation. Reduce memory overhead and improve performance.

4, Convertview's Settag ():

use the Settag () method to attach the Viewholder object as a label to the Convertview, when Convertview is reused because there are viewholder objects on it, So Convertview has several attributes in the Viewholder, thus saving the Findviewbyid () process. If an item has three controls, if there are 100 item, then in the process of loading data, it is equivalent to save hundreds of times Findviewbyid (), save the time of executing Findviewbyid (), increase the loading speed, save the cost of performance.

5. The inflate () method of the Layoutinflater object:

The inflate () method generally receives two parameters, the first parameter is the layout ID to be loaded, and the second parameter refers to the outside of the layout and then nested a layer of parent layout, if you do not need to directly pass NULL.

The inflate () method also has a method overload that receives three parameters

1. If Root is null,attachtoroot will lose its function, setting any value is meaningless. 2. If root is not set to true for Null,attachtoroot, the root layout is then nested in the outermost layer of the loaded layout file. 3. If root is not set to False for Null,attachtoroot, the root parameter loses effect. 4. If the Attachtoroot parameter is not set, the default is true if root is not the Null,attachtoroot parameter.

So in use Layoutinflater When filling the layout, be aware of the parameters of the inflate () method. If it is two arguments, the second parameter can be null, and if you use the three-parameter method, pay attention to the collocation of the parameters.

6, monitor the scrolling status of the screen change situation:

The ListView object has a Onscrolllistener listener. The second parameter of its callback method onscrollstatechanged (Abslistview view, int scrollstate) is the screen scrolling state.

Scrollstate = Scroll_state_touch_scroll (1): Indicates that scrolling is in progress. 1 when the screen scrolls and the user uses a touch or finger that is still on the screen

Scrollstate =scroll_state_fling (2): Indicates that the finger does the action of throwing (the finger leaves the screen, a hard slide, the screen produces inertia sliding).

Scrollstate =scroll_state_idle (0): Indicates that the screen is stopped. 0 when the screen stops scrolling.

in the above three screen scrolling states, if you are still in Scroll_state_fling state, the screen is still in an inertial slide state, and the picture can not be loaded asynchronously. This saves you the unnecessary performance overhead.

qianfeng-android-day08-Basic Learning: the ListView

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.