Android User Interface UI components-adapterview and its sub-classes (1) Details of listview and various adapters

Source: Internet
Author: User

Listview is a list component. It generally uses the system-provided listview by inheriting listactivity.

All adapterview components must have a corresponding adapter as the adapter to display the layout of elements in the list.

See Mind Map


Arrayadapter: array or set adapter.

Example:
Private final string [] MOUs = {
"Guo jia ",
"Zookeeper ",
"Zookeeper ",
"Cheng Jing ",
"Drama talents ",
"Xu Shu"
};
Arrayadapter <string> adapter = new arrayadapter <string> (this, Android. R. layout. simple_list_item_1, MoUs );

You can also use the Android: entries attribute in the XML file to specify the bound array resource file.
Resource files are stored in the value folder.
For example:
Android: entries = "@ array/book"

<String-array name = "book">
<Item> 1 </item>
<Item> 2 </item>
<Item> 3 </item>
<Item> 3 </item>
</String-array>


Example

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="horizontal" >    <ListView        android:id="@+id/lv"        android:layout_width="match_parent"        android:layout_height="match_parent"        /></LinearLayout>

Package COM. light. android. study; import android. app. activity; import android. OS. bundle; import android. widget. arrayadapter; import android. widget. listview; public class mainactivity extends activity {private final string [] MOUs = {"guo jia", "zhuyun", "zhuyun", "Cheng Jing", "Opera talent ", "Xu Shu"}; private listview lv; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); Init (); initadapter ();} private void Init () {Lv = (listview) findviewbyid (R. id. LV);} private void initadapter () {arrayadapter <string> adapter = new arrayadapter <string> (this, android. r. layout. simple_list_item_1, MoUs); LV. setadapter (adapter );}}

Effect:

Simpleadapter: simple adapter implementation

Simpleadapter (context, list <? Extends Map <string,?> Data, int resource, string [] From, int [])
The first parameter is the context object.
The second parameter is a list object consisting of map that stores each row of data. That is to say, each attribute in each row of data is composed of its name and its value, multiple attributes have multiple key-value pairs. Multiple key-value pairs in each row constitute a map object in this row. The map object in this row corresponds to this list.
Third parameter layout File ID
Key Value of multiple key-value pairs in the map object of the fourth Parameter
Component ID used to display content in the fifth parameter layout File


Simpleadapter binds data to a view in two phases
1. first, if simpleadapter is set. viewbinder, The setviewvalue (Android. view. view, object, string) will be called. if the returned value of setviewvalue is true, the binding is completed and the default binding implementation is no longer called.
2. If the returned value is false, the view binds data in the following order:
• If view implements checkable (for example, checkbox), it is expected that the bound value is a boolean type.
• Textview. The expected bind value is a string type, which is bound by calling setviewtext (textview, string.
• Imageview: It is expected that the bound value is a resource ID or a string. You can call setviewimage (imageview, INT) or setviewimage (imageview, string) to bind data.
If no suitable binding occurs, illegalstateexception will be thrown.

Example:

Layout file:

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns: Tools = "http://schemas.android.com/tools" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <! -- Define a list --> <listview Android: Id = "@ + ID/mylist" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> </linearlayout>

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns: Tools = "http://schemas.android.com/tools" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: Orientation = "vertical"> <! -- Define an imageview as part of the list item. --> <Imageview Android: Id = "@ + ID/Header" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: paddingleft = "10dp" tools: ignore = "contentdescription"/> <! -- Defines a textview that is used as part of the list item. --> <Textview Android: Id = "@ + ID/Name" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: gravity = "center_vertical" Android: paddingleft = "10dp" Android: textsize = "16sp"/> </linearlayout>

Package COM. light. android. study; import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; import Java. util. map; import android. app. activity; import android. OS. bundle; import android. widget. listview; import android. widget. simpleadapter; public class mainactivity extends activity {private string [] names = new string [] {"Du Fu", "Xiyu", "Qingzhao", "Li Bai "}; private int [] imageids = new int [] {R. drawable. tiger, R. drawable. nongyu, R. drawable. qingzhao, R. drawable. libai}; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); List <Map <string, Object> listitems = new arraylist <Map <string, Object> (); For (INT I = 0; I <names. length; I ++) {Map <string, Object> map = new hashmap <string, Object> (); map. put ("Header", imageids [I]); map. put ("personname", Names [I]); listitems. add (MAP);} // construct simpleadaptersimpleadapter simpleadapter = new simpleadapter (this, listitems, R. layout. list_item_layout, new string [] {"personname", "Header"}, new int [] {R. id. name, R. id. header}); listview list = (listview) findviewbyid (R. id. mylist); list. setadapter (simpleadapter );}}

Effect:



Cursoradapter:

Cursor collection adapter, a bridge to the database
The result set carried by the cursor must contain a column named "_ id". Otherwise, this class cannot work.
Getview ()
Settings displayed for each item
BindView ()
Bind the data with the generated View
Newview ()
Create a view
Implementation of the getview source code in cursoradapter
Public View getview (INT position, view convertview, viewgroup parent ){
View V;
If (convertview = NULL ){
V = newview (mcontext, mcursor, parent );
} Else {
V = convertview;
}
BindView (v, mcontext, mcursor );
Return V;
}
Getview first uses an existing view. If not, newview is called to generate one, and bind the data.

We generally use its subclass simplecursoradapter to implement the adapter of the queried data list.

Simplecursoradapter (context, int layout, cursor C, string [] From, int [] to, int flags)
Context: current context object
Layout: Layout File ID
C: Set
From: name of the column in the set to be bound
To: display the view Id set of the project, which is defined in the layout file.
Flags: used to identify the behavior of the adapter
We recommend that you use cursoradapter. flag_register_content_observer.
The adapter registers a content observer on the cursor and calls the oncontentchanged () method when the notification arrives. when using this flag, note that when registering the observer, you must first remove the association between the current cursor and the adapter to prevent leakage.
In Android 3.0, cursorloader is introduced to asynchronously load data. In order to avoid blocking the UI thread when querying the database synchronously. Therefore, we usually leave the cursor object in simplecursoradapter empty first, then load data with the cursorloader object, and then put it into the adapter.
Example:

Layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="horizontal" >    <ListView        android:id="@android:id/list"        android:layout_width="match_parent"        android:layout_height="match_parent"        /></LinearLayout>

Item layout file:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              xmlns:tools="http://schemas.android.com/tools"              android:layout_width="match_parent"               android:layout_height="64dip"               android:orientation="horizontal"               android:gravity="center_vertical"               android:paddingLeft="8dip">                              <TextView android:id="@android:id/text1"                          android:layout_width="match_parent"                         android:layout_height="wrap_content"                          android:textSize="18sp"                          android:gravity="center_vertical"                          android:singleLine="true"                          android:fadingEdge="horizontal"                          android:fadingEdgeLength="3dip"                          android:ellipsize="marquee"                          /> </LinearLayout>

Package COM. light. android. study; import android. app. listactivity; import android. app. loadermanager. loadercallbacks; import android. content. context; import android. content. cursorloader; import android. content. loader; import android. database. cursor; import android. OS. bundle; import android. provider. contactscontract; import android. widget. simplecursoradapter; // The actual interface is cursorloaderpublic class mainactivity exten DS listactivity implements loadercallbacks <cursor> {private simplecursoradapter madapter; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); // create an empty adapter we will use to display the loaded data. madapter = new simplecursoradapter (mainactivity. this, R. layout. contacts_list_item, null, new string [] {contactsco Ntract. contacts. display_name}, new int [] {android. r. id. text1}, 0); getlistview (). setadapter (madapter); // initialize loader // The first identifier indicates the unique ID of the loader object. The second optional parameter is used to support the loader construction method, // The third parameter is the loadercallbacks interface type getloadermanager (). initloader (0, null, this);} public loader <cursor> oncreateloader (int id, bundle ARGs) {// operations that consume a lot of time, such as reading data from the database, are stored in // onloadinbackgroundreturn new mycursorloader (getapplicat Ioncontext ();} public void onloadfinished (loader <cursor> arg0, cursor) {// swap the new cursor in. (the Framework will take care of closing the // old cursor once we return .) madapter. swapcursor (cursor);} public void onloaderreset (loader <cursor> arg0) {// This is called when the last cursor provided to onloadfinished () // above is about to be closed. we need to make sure we are no // longer Using it. madapter. swapcursor (null);} public static class mycursorloader extends cursorloader {string [] mcontactprojection = {contactscontract. contacts. _ id, contactscontract. contacts. display_name}; private context mcontext; Public mycursorloader (context) {super (context); mcontext = context;}/*** 4. the onloadinbackground * of the custom cursorloader returns a cursor. Here, we use * to fill the data with simplecursoradapter. Query data and perform other operations here */@ overrideprotected cursor onloadinbackground () {cursor = mcontext. getcontentresolver (). query (contactscontract. contacts. content_uri, mcontactprojection, null); Return cursor ;}}}

Effect:


Finally, let's take a look at the custom baseadapter.

You need to implement the following methods:

Abstract object getitem (INT position)
Obtain the position item.
Abstract int getcount ()
Obtain the total number of projects.
Abstract long getitemid (INT position)
Obtain the ID of the position item.
Abstract int getitemviewtype (INT position)
Obtain the type of the position item.
Abstract view getview (INT position, view convertveiw, viewgroup parent)
Settings displayed for each item
In the getview method, view optimization listview needs to be cached and loaded.

Viewholder is officially recommended, which is a singleton.
Example:

@Override public View getView(int position, View convertView, ViewGroup parent) {  ViewHolder holder;  if (convertView == null) {     final LayoutInflater inflater = (LayoutInflater)                        mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);      convertView = inflater.inflate(R.layout.list_item_icon_text, null);       holder = new ViewHolder();        holder.icon = (ImageView) convertView.findViewById(R.id.icon);       holder.text = (TextView) convertView.findViewById(R.id.text);       convertView.setTag(holder);  } else {       holder = (ViewHolder) convertView.getTag();  }       holder.icon.setImageResource(R.drawable.icon);       holder.text.setText(mData[position]);       return convertView; } static class ViewHolder {     ImageView icon;     TextView text; } 

 

 




 

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.