Idea and code of ListView of Android custom Adapter

Source: Internet
Author: User

In development, we often use the ListView control. The Android API also provides many shortcuts for creating ListView adapters. For example, ArrayAdapter, SimpleAdapter, and SimpleCursorAdapter. But do you find that if you use the adapters provided by these systems, the response to the event can only be limited to one row unit. If a row contains a button and an image control, the response operations between them are different. If the system adapter is used, the response events of each control cannot be precise. In this case, we generally use a custom adapter to implement this precise request.

Create a ListView with two elements:

1) dataset, that is, the string to be mapped, image information, and so on.

2) the adapter maps the string and Image information to be mapped into a view (such as Textview and Image) and adds it to the ListView.

Implementation Details:

1. Create a dataset, which is generally defined as follows:

Copy codeThe Code is as follows: private List <Map <String, Object> listItems;

Element addition method:Copy codeThe Code is as follows: Map <String, Object> map = new HashMap <String, Object> ();

Map. put ("image", imgeIDs [I]); // image resource

Map. put ("title", "item name:"); // item title

Map. put ("info", goodsNames [I]); // Item Name

Map. put ("detail", goodsDetails [I]); // item details

ListItems. add (map); // add an item

2. Create an adapter

Copy codeThe Code is as follows: public class ListViewAdapter extends BaseAdapter {......} // The Custom adapter generally inherits the BaseAdapter class

ListViewAdapter = new ListViewAdapter (this, listItems );

3. Set an adapter for ListViewCopy codeThe Code is as follows: listView. setAdapter (listViewAdapter );

4. Here is another key point: how to add the list_item.xml layout as a view to the listView:Copy codeThe Code is as follows: LayoutInflater listContainer; // view the container factory

ListContainer = LayoutInflater. from (context); // create a view container factory and set the context

ConvertView = listContainer. inflate (R. layout. list_item, null); // create a view of the list_item.xml layout File

The instance view is as follows:

1) Layout file main. xml

Copy codeThe Code is as follows: <? Xmlversion = "1.0" encoding = "UTF-8"?>
<LinearLayoutxmlns: Android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">

<! -- Settlement -->
<LinearLayoutAndroid: gravity = "center_horizontal"
Android: orientation = "horizontal" android: layout_width = "fill_parent"
Android: layout_height = "wrap_content">
<TextViewAndroid: text = "Settlement :"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: textColor = "# FFFFFFFF"
Android: textSize = "20px"/>
<ImageButtonAndroid: id = "@ + id/imgbt_sum"
Android: layout_width = "40px"
Android: layout_height = "40px"
Android: background = "@ drawable/shopping"/>
</LinearLayout>

<TextViewAndroid: text = "item list :"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: textColor = "# FFFFFFFF"/>

<! -- Item list -->
<ListViewAndroid: id = "@ + id/list_goods"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"/>

</LinearLayout>

List_item.xmlCopy codeThe Code is as follows: <? Xmlversion = "1.0" encoding = "UTF-8"?>
<LinearLayoutxmlns: Android = "http://schemas.android.com/apk/res/android"
Android: orientation = "horizontal" android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">

<! -- Product image -->
<ImageViewAndroid: id = "@ + id/imageItem"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_margin = "5px"/>

<! -- Product information -->
<LinearLayoutAndroid: orientation = "vertical"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content">

<TextViewAndroid: id = "@ + id/titleItem"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: textColor = "# FFFFFFFF"
Android: textSize = "13px"/>
<TextViewAndroid: id = "@ + id/infoItem"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: textColor = "# FFFFFFFF"
Android: textSize = "22px"/>
</LinearLayout>

<! -- Purchase and product details -->
<LinearLayoutAndroid: gravity = "right"
Android: orientation = "horizontal" android: layout_width = "fill_parent"
Android: layout_height = "wrap_content">
<CheckBoxAndroid: id = "@ + id/checkItem"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_margin = "5px"/>
<Button Android: id = "@ + id/detailItem"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_margin = "5px"/>
</LinearLayout>
</LinearLayout>

2) code, master code:

Copy codeThe Code is as follows: package com. myAndroid. test;

Import java. util. ArrayList;
Import java. util. HashMap;
Import java. util. List;
Import java. util. Map;

Import Android. app. Activity;
Import Android. app. AlertDialog;
Import Android. content. DialogInterface;
Import Android. OS. Bundle;
Import Android. view. View;
Import Android. view. View. OnClickListener;
Import Android. widget. ArrayAdapter;
Import Android. widget. ImageButton;
Import Android. widget. ListView;

Publicclass MyListView extends Activity {

Private ListView listView;
Private ImageButton imgbt_sum;
Private ListViewAdapter listViewAdapter;
Private List <Map <String, Object> listItems;
Private Integer [] imgeIDs = {R. drawable. cake,
R.drawable.gif t, R. drawable. letter,
R. drawable. love, R. drawable. mouse,
R. drawable. music };
Private String [] goodsNames = {"cake", "gift ",
"Stamp", "love", "Mouse", "music CD "};
Private String [] goodsDetails = {
"Cake: Delicious. ",
"Gift: the gift is light and heavy. ",
"Stamp: traveling around the world. ",
"Love: The world has love. ",
"Mouse: agile. ",
"Music CD: Cool music. "};

/** Called when the activity is first created .*/
@ Override
Publicvoid onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );

ListView = (ListView) findViewById (R. id. list_goods );
Imgbt_sum = (ImageButton) findViewById (R. id. imgbt_sum );
Imgbt_sum.setOnClickListener (new ClickEvent ());
ListItems = getListItems ();
ListViewAdapter = new ListViewAdapter (this, listItems); // create an adapter
ListView. setAdapter (listViewAdapter );
}

/**
* Initialize Product Information
*/
Private List <Map <String, Object> getListItems (){
List <Map <String, Object> listItems = new ArrayList <Map <String, Object> ();
For (int I = 0; I <goodsNames. length; I ++ ){
Map <String, Object> map = new HashMap <String, Object> ();
Map. put ("image", imgeIDs [I]); // image resource
Map. put ("title", "item name:"); // item title
Map. put ("info", goodsNames [I]); // Item Name
Map. put ("detail", goodsDetails [I]); // item details
ListItems. add (map );
}
Return listItems;
}

Class ClickEvent implements OnClickListener {

@ Override
Publicvoid onClick (View v ){
// TODO Auto-generated method stub
String goodsList = "";
For (int I = 0; I <listItems. size (); I ++ ){
GoodsList + = listViewAdapter. hasChecked (I )? GoodsNames [I] + "":"";
}
New AlertDialog. Builder (MyListView. this)
. SetTitle ("shopping list :")
. SetMessage ("Hello, you have selected the following item: \ n" + goodsList)
. SetPositiveButton ("OK", null)
. Show ();
}

}
}

Adapter code:

Copy codeThe Code is as follows: package com. myAndroid. test;

Import java. util. List;
Import java. util. Map;

Import Android. app. AlertDialog;
Import Android. content. Context;
Import Android. util. Log;
Import Android. view. LayoutInflater;
Import Android. view. View;
Import Android. view. ViewGroup;
Import Android. widget. BaseAdapter;
Import Android. widget. Button;
Import Android. widget. CheckBox;
Import Android. widget. CompoundButton;
Import Android. widget. ImageView;
Import Android. widget. ListView;
Import Android. widget. TextView;

Publicclass ListViewAdapter extends BaseAdapter {
Private Context context; // running Context
Private List <Map <String, Object> listItems; // a collection of item information
Private LayoutInflater listContainer; // view container
Privateboolean [] hasChecked; // records the selected product status
Publicfinalclass ListItemView {// set of Custom Controls
Public ImageView image;
Public TextView title;
Public TextView info;
Public CheckBox check;
Public Button detail;
}

Public ListViewAdapter (Context context, List <Map <String, Object> listItems ){
This. context = context;
ListContainer = LayoutInflater. from (context); // create a view container and set the context
This. listItems = listItems;
HasChecked = newboolean [getCount ()];
}

Publicint getCount (){
// TODO Auto-generated method stub
Return listItems. size ();
}

Public Object getItem (int arg0 ){
// TODO Auto-generated method stub
Returnnull;
}

Publiclong getItemId (int arg0 ){
// TODO Auto-generated method stub
Return0;
}

/**
* Records the selected items.
* @ Param checkedID: the serial number of the selected item
*/
Privatevoid checkedChange (int checkedID ){
HasChecked [checkedID] =! HasChecked [checkedID];
}

/**
* Determine whether an item is selected
* @ Param checkedID: item No.
* @ Return indicates whether to check the selected status.
*/
Publicboolean hasChecked (int checkedID ){
Return hasChecked [checkedID];
}

/**
* Display item details
* @ Param clickID
*/
Privatevoid showDetailInfo (int clickID ){
New AlertDialog. Builder (context)
. SetTitle ("item details:" + listItems. get (clickID). get ("info "))
. SetMessage (listItems. get (clickID). get ("detail"). toString ())
. SetPositiveButton ("OK", null)
. Show ();
}

/**
* ListView Item settings
*/
Public View getView (int position, View convertView, ViewGroup parent ){
// TODO Auto-generated method stub
Log. e ("method", "getView ");
Finalint selectID = position;
// Custom View
ListItemView listItemView = null;
If (convertView = null ){
ListItemView = new ListItemView ();
// Obtain the view of the list_item layout File
ConvertView = listContainer. inflate (R. layout. list_item, null );
// Obtain the control object
ListItemView. image = (ImageView) convertView. findViewById (R. id. imageItem );
ListItemView. title = (TextView) convertView. findViewById (R. id. titleItem );
ListItemView.info = (TextView) convertView. findViewById (R. id. infoItem );
ListItemView. detail = (Button) convertView. findViewById (R. id. detailItem );
ListItemView. check = (CheckBox) convertView. findViewById (R. id. checkItem );
// Set the control set to convertView
ConvertView. setTag (listItemView );
} Else {
ListItemView = (ListItemView) convertView. getTag ();
}
// Log. e ("image", (String) listItems. get (position). get ("title"); // Test
// Log. e ("image", (String) listItems. get (position). get ("info "));

// Set text and images
ListItemView. image. setBackgroundResource (Integer) listItems. get (
Position). get ("image "));
ListItemView. title. setText (String) listItems. get (position)
. Get ("title "));
ListItemView.info. setText (String) listItems. get (position). get ("info "));
ListItemView. detail. setText ("product details ");
// Click "register" to love you
ListItemView. detail. setOnClickListener (new View. OnClickListener (){
@ Override
Publicvoid onClick (View v ){
// Display item details
ShowDetailInfo (selectID );
}
});
// Register the multi-choice box status event processing
ListItemView. check
. SetOnCheckedChangeListener (new CheckBox. OnCheckedChangeListener (){
@ Override
Publicvoid onCheckedChanged (CompoundButton buttonView,
Boolean isChecked ){
// Record the item selection status
CheckedChange (selectID );
}
});

Return convertView;
}
}

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.