[Android game development 23] custom ListView [general] adapter and Listener Control!

Source: Internet
Author: User

 

ListView: it is one of the most commonly used system components in the Android Application development process. Of course, some kids may ask why this is suddenly mentioned in game development, system components, such as game rankings and simple game level selection, can also be implemented using ListView;

Of course, I think everyone will use ListView. This article does not explain how ListView is used, but how to customize a [general] adapter class;

Among the three ListView adapters, the most popular one is the SimpleAdapter adapter, which is widely known to all the children's shoes, you can use a custom Layout for each item in the ListView and insert N multiple components. However, SimpleAdapter also has a weakness, that is, when each item in the ListView has buttons, CheckBox, and other event-related components, to listen to them, we must customize the adapters! The focus today is to explain how to write a custom universal adapter class!

When SimpleAdapter is constructed, we know that five parameters are required to map data to ListView. Therefore, today's custom universal adapter is actually a custom version of SimpleAdapter;

Okay, maybe I have said so much, but you still don't know much about it. In fact, there are three advantages of the custom universal adapter to be described today:

1. When using a universal adapter, you do not need to write a new one every time you use a custom Adapter. It is too tired ....

2. the constructor is the same as the SimpleAdapter constructor. The five parameters are the same!

3. You only need to set the listening component in the Custom adapter class! Other code does not need to be modified!

 

For example, we need to complete this ListView:

(Figure 1)

 

First, we will complete the layout of each item in the ListView:

Main. xml:

 

<? Xml version = "1.0" encoding = "UTF-8"?>

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"

Android: orientation = "horizontal"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

>

<ImageView

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: id = "@ + id/iv"

/>

<LinearLayout

Android: orientation = "vertical"

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

>

<TextView

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: textSize = "20sp"

Android: id = "@ + id/bigtv"

/>

<TextView

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: textSize = "10sp"

Android: id = "@ + id/smalltv"

/>

</LinearLayout>

<Button

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: text = "button"

Android: id = "@ + id/btn"

/>

<CheckBox

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: id = "@ + id/cb"

/>

</LinearLayout>

 

 

Modify source code: MainActivity. java:

 

Public class MainActivity extends Activity {

Private SimpleAdapter adapter; // declare an adapter object

Private ListView listView; // declares a list view object

Private List <Map <String, Object> list; // declare the List container

Public static MainActivity ma;

@ Override

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

Ma = this;

// Instantiate the list container

List = new ArrayList <Map <String, Object> ();

ListView = new ListView (this); // instantiate the List View

// A list data container of the Instance

Map <String, Object> map = new HashMap <String, Object> ();

// Add data to the list container

Map. put ("itemincluimageivew", R. drawable. icon );

Map. put ("item1_bigtv", "BIGTV ");

Map. put ("item1_smalltv", "SMALLTV ");

// Add the list data to the list container

List. add (map );

// -- The system adapter cannot be used for component listening;

/// Instance Adapter

Adapter = new SimpleAdapter (this, list, R. layout. main, new String [] {

"Item1_imageivew", "item1_bigtv", "item1_smalltv"}, new int [] {

R. id. iv, R. id. bigtv, R. id. smalltv });

ListView. setAdapter (adapter );

/// Display the List View

This. setContentView (listView );

}

}

 

At this point, the ListView that we previously requested to complete (figure 1) is required. [Baidu and google, which are unfamiliar with ListView, should learn the basics first]

Of course, here we just finished the interface. If you want to listen to the buttons and check box events (Figure 1), you must customize an adapter. The following describes how to implement a universal adapter:

Create a new class named "MySimpleAdapter. java" that inherits BaseAdapter:

 

/**

*

*/

Package com. himi;

Import java. util. List;

Import java. util. Map;

Import android. app. AlertDialog;

Import android. content. Context;

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. TextView;

Import android. widget. CompoundButton. OnCheckedChangeListener;

/**

* @ Author Himi

*

*/

Public class MySimpleAdapter extends BaseAdapter {

Private LayoutInflater mInflater;

Private List <Map <String, Object> list;

Private int layoutID;

Private String flag [];

Private int ItemIDs [];

Public MySimpleAdapter (Context context, List <Map <String, Object> list,

Int layoutID, String flag [], int ItemIDs []) {

This. mInflater = LayoutInflater. from (context );

This. list = list;

This. layoutID = layoutID;

This. flag = flag;

This. ItemIDs = ItemIDs;

}

@ Override

Public int getCount (){

// TODO Auto-generated method stub

Return list. size ();

}

@ Override

Public Object getItem (int arg0 ){

// TODO Auto-generated method stub

Return 0;

}

@ Override

Public long getItemId (int arg0 ){

// TODO Auto-generated method stub

Return 0;

}

@ Override

Public View getView (int position, View convertView, ViewGroup parent ){

ConvertView = mInflater. inflate (layoutID, null );

For (int I = 0; I <flag. length; I ++) {// Note 1

If (convertView. findViewById (ItemIDs [I]) instanceof ImageView ){

ImageView iv = (ImageView) convertView. findViewById (ItemIDs [I]);

Iv. setBackgroundResource (Integer) list. get (position). get (

Flag [I]);

} Else if (convertView. findViewById (ItemIDs [I]) instanceof TextView ){

TextView TV = (TextView) convertView. findViewById (ItemIDs [I]);

TV. setText (String) list. get (position). get (flag [I]);

} Else {

//... Note 2

}

}

AddListener (convertView );

Return convertView;

}

/**

* You only need to write the component that needs to set the listening event in the following method!

* No changes are required!

* Note 3

*/

Public void addListener (View convertView ){

(Button) convertView. findViewById (R. id. btn). setOnClickListener (

New View. OnClickListener (){

@ Override

Public void onClick (View v ){

New AlertDialog. Builder (MainActivity. ma)

. SetTitle ("Custom generic SimpleAdapter ")

. SetMessage ("the button successfully triggers the listener event! ")

. Show ();

}

});

(CheckBox) convertView. findViewById (R. id. cb )).

SetOnCheckedChangeListener (new OnCheckedChangeListener (){

@ Override

Public void onCheckedChanged (CompoundButton buttonView, boolean isChecked ){

New AlertDialog. Builder (MainActivity. ma)

. SetTitle ("Custom generic SimpleAdapter ")

. SetMessage ("CheckBox successfully triggers the listener event of status change! ")

. Show ();

}

});

}

}

 

 

Note 1: This For Loop determines the type of each component contained in each item in ListView and sets its data!

Some children's shoes may be unfamiliar with the keyword "instanceof", which is a judgment on the Object type;

Here I only recognize the data of ImageView and TextView types. Why do I only write these two types here, this is because buttons, CheckBox, and other components with event response cannot be mapped to the ListView through the adapter;

 

In fact, for the adapter ing mechanism, let's briefly describe the following: for example, when a TextView component is added to put () in each item (List) of ListView, put () the first parameter key in the method is known as the value used for ing data with the adapter, so the second parameter is actually put into the component data; in fact, when the data is reflected in ListViw, the component is actually instantiated internally and data is set for the component;

 

 

NOTE 2: I have an else {...} this is for the kids shoes to expand, because there may be some other ing components, so the interface is left here for everyone to expand;

 

NOTE 3: addListener (View convertView) is the method I have left. Students only need to write the component that needs to set the listener event in this method!

 

Let's take a look at the effect of using a universal listener:

 

 

 

OK, it's normal! Let's take a look at the comparison between SimpleAdapter and our custom MySimpleAdapter code:

 

How about it! The construction parameters are exactly the same, and we are more powerful than it. We only need to set the listening code of the component to be monitored.

Wahaha, okay. Let's get there today. I hope this universal adapter will be useful to everyone!

Supplement: when you use a custom adapter, sometimes the focus of each item in the ListView is lost. For example, in this article, the focus is intercepted by the Button and CheckBox, as long as the focus settings of the button and checkBox are invisible, it is OK. ~

In xml, focusable is the property. android: focusable = "false"

Here, we also remind kids shoes who develop games. Many game developers think that developing games do not need to learn how to use system components, or be contaminated with xml or layout, in fact, it is a big mistake for you to think so. The beauty of the components of Android accounts for a heavy proportion. It is not a waste of such beautiful components !! I hope game developers who are not familiar with the components will learn how to use the components!

 

Source code download: http://www.bkjia.com/uploadfile/2011/1115/20111115053333156.rar

Himi original, reprinted must indicate the source!

 

 

Address: http://blog.csdn.net/xiaominghimi/archive/2011/04/11/6314704.aspx

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.