In the Android Application project, three adapters are provided: BaseAdapter, SimpleAdapter, and ArrayAdapter.

Source: Internet
Author: User

In the Android Application project, three adapters are provided: BaseAdapter, SimpleAdapter, and ArrayAdapter.

I. Preface:

Here, we will explain three adapters for Android apps: BaseAdapter, SimpleAdapter, and ArrayAdapter. The commonly used is BaseAdapter, which is also recommended by individuals.

2. In-depth understanding:

1. What is an adapter?

Adapter: In Android, as the name implies, data is converted into a form that conforms to the interface style and displayed through ListView. That is to say, the adapter serves as a bridge between data and interfaces.

The adapter acts as a converter in the data (backend) and display page (front-end) of the database, data in the database (such as arrays, linked lists, databases, collections, etc) data that can be normally displayed on a mobile phone page that is changed to a category through an adapter. It can be seen as an understanding of interface data binding. Assume that the data, Adapter, and ListView (PAGE) are compared to an MVC pattern, then the Adapter acts as the Controller in the middle.

  

2. Why does the object set the data source?

Generally, data conversion is provided for ListView. Of course, the GridView [grid view], Spinner [drop-down list], Gallery [Gallery], and ViewPage all require an adapter to set the data source for them.

 

Iii. Sample Code:

ArrayAdapter example:

Requirement: Use the array adapter to output the corresponding data to the ListView.

1. First, create an Android project, then define a ListView in the layout file, and set relevant properties:

<RelativeLayout 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" >    <ListView        android:id="@+id/listView"        android:layout_width="match_parent"        android:layout_height="wrap_content"/></RelativeLayout>

 

2. Second, write the code in the activity class. For details, see the code and add related comments to the code.

Package com. mqz. android_arrayadapter; import android. app. activity; import android. OS. bundle; import android. widget. arrayAdapter; import android. widget. listView; public class MainActivity extends Activity {private ListView listView; // defines the ListView control in the layout file private String [] city = {"Guangzhou", "Shenzhen ", "Beijing", "Shanghai", "Hong Kong", "Macao", "Tianjin"}; // defines an array as the data source private ArrayAdapter <String> arrayAdapter; // define an array adapter object @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listView = (ListView) findViewById (R. id. listView); // obtain the ListView control object in the layout File

/** Context context, the Context object * int resource, the layout style displayed by the items item, which is generally the layout text android. r. layout. ** (however, You need to select a layout file that is suitable for ListView, or an error is reported during running.) * String [] objects array object (Data Source) *** // create an array adapter object, you can also set the layout style and Data Source arrayAdapter = new ArrayAdapter <String> (MainActivity. this, android. r. layout. simple_list_item_1, city); // load the array adapter to the ListView control listView. setAdapter (arrayAdapter );}}

 

3. Running result: we do not need to define the content in the TextView control by ourselves. This goal is achieved through the array adapter.

        

  

    

SimpleAdapter example:

Requirement: Fill in the background data to the page, including TextView and ImageView to be filled, that is, display the name and image to the page.

1. First, create an android project and add a ListView control to the main layout file.

<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="horizontal"    tools:context="com.mqz.android_simpleadapter.MainActivity" >            <ListView         android:id="@+id/listView"        android:layout_width="match_parent"        android:layout_height="match_parent"        ></ListView></LinearLayout>

 

2. Second, write the code in the Activity class with comments, as shown below:

  

Package com. mqz. android_simpleadapter; 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. view. view; import android. widget. adapterView; import android. widget. adapterView. onItemClickListener; import android. widget. listView; import android. widget. simpleAdapter; import android. widget. textView; impo Rt android. widget. toast; public class MainActivity extends Activity {private ListView listView; // defines the ListView object, which is used to obtain the private String [] name = {"James", "Xiaohua ", "xiaoliang", "Xiao Wang", "Xiao Lin", "Xiao Zhao"}; // defines an array of names to provide private int [] images = {R. drawable. one, R. drawable. two, R. drawable. three, R. drawable. four, R. drawable. five, R. drawable. six}; // defines an integer array for the profile picture private List in the data source <Map <String, Object> list_map = new ArrayList <Map <String, Object> (); // defines an adapter Object @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listView = (ListView) findViewById (R. id. listView); // get the ListView object in the layout file // 1. prepare the data source and add data to listView cyclically (prepare the data source, here we simulate querying data from SQLite) for (int I = 0; I <6; I ++) {Map <String, Object> items = new HashMap <String, Object> (); // create a key value Map set, used to store the name and Avatar items. put ("pic", images [I]); // put the Avatar and obtain the array items according to the subscript. put ("name", name [I]); // enter the name and obtain the array list_map.add (items) based on the subscript ); // put the Map set that stores the data into the list, this completes the preparation of the class data source} // 2. Creates an adapter (you can use an external class or an internal class) SimpleAdapter simpleAdapter = new SimpleAdapter (MainActivity. this,/* pass in a context as the parameter */list_map,/* pass in the corresponding data source, this data source is not only a mixture of data but also coupled with the interface. */R. layout. list_items,/* set the layout of an items, instead of the layout of the ListView control */new String [] {"pic", "name "}, /* input the name of the key-Value Pair defined above. The corresponding value is automatically found based on the input key */new int [] {R. id. items_imageView1, R. id. items_textView1});/* You need to specify the input control in the items layout file. Here, you can directly upload the id. * // 3. Add the adapter listView to the listView. setAdapter (simpleAdapter );});}}

A detailed explanation of the parameter relationship in adaptation:

  

 

3. Create the layout file for the item:

The layout file of the item is as follows:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <ImageView        android:id="@+id/items_imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        />    <TextView        android:id="@+id/items_textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="52dp"/>    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/items_textView2"        android:text="hello android!"        android:layout_alignParentRight="true"        />        </RelativeLayout>

 

4. Running result:

        

 

 

   

BaseAdapter example:

1. After creating an android project, create a new package and define a User entity class (used for subsequent data sources) in the sub-package. You can simply define one or two attributes, this is just a test. (Simulate querying data from the database .)

        

 

2. Write the main code in the MainActivity class:

Package com. mqz. android_baseadapter_one; import java. util. arrayList; import java. util. list; import android. app. activity; import android. OS. bundle; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. imageView; import android. widget. listView; import android. widget. textView; import com. mqz. android_baseAdapter_one_en Tity. user; public class MainActivity extends Activity {private ListView listView; // defines the ListView control, used to obtain the ListView private List <User> list in the layout file; // stores your collection of data sources, set the generic type to the User type. Private int [] images = {R. drawable. one, R. drawable. two, R. drawable. three, R. drawable. four, R. drawable. five,}; // defines the array and saves the image Id. It is used to set the profile picture private String [] names = {"Zhang San", "Li Si", "Wang Wu", "Zhao Liu ", "Tianqi"}; // defines a string array to save the user's name @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listView = (ListView) findViewById (R. id. listView); // get the ListView Control File // 1. Load the data source. Here, we only simulate an operation to query data from the database. (Simulate database data query operations) list = new ArrayList <User> (); for (int I = 0; I <5; I ++) {User u = new User (); u. setName (names [I]); // sets the name and u according to the defined array. setPic (images [I]); // defines the Avatar, which must be an integer in the object class, because all the resource files in the R file are an integer. List. add (u); // add the object to the list set. The data source is prepared successfully.} // 2. create a BaseAdapter adapter and configure the corresponding layout file (this time using the internal class method) // 3. load the adapter to ListView. MyBaseAdapter adapter = new MyBaseAdapter (); // create the object listView of the member's internal class. setAdapter (adapter); // set the adapter for the data source} class MyBaseAdapter extends BaseAdapter {// get the size of the current items item, it can also be viewed as the data source size @ Override public int getCount () {return list. size () ;}// obtain the View Object @ Override public Object getItem (int position) based on the item subscript {// TODO Auto-generated method Stub return null;} // obtain the items id @ Override public long getItemId (int position) {// TODO Auto-generated method stub return 0 ;} // obtain the view object/** int position based on the subscript of the input item, which indicates the subscript in the listView where the item is located and the data corresponding to the subscript in the data source * View convertView, cache Mechanism. When some items slide out of the screen, a new View object will be created, which will occupy memory resources. * use convertView to determine whether it is null, if it is null, the item is not flushed out. You need to create a new view object * if it is not empty, it indicates that the class screen has been flushed out. Therefore, use convertView, view = convertView, * convert can be understood as a slide-out View object * ViewGroup parent view group object, that is, the ListView object to which the currently drawn items item belongs. **/@ Override public View getView (int position, View convertView, ViewGroup parent) {View view = null; // gets the padding object. This object can help us draw items, there are multiple ways to obtain: // LayoutInflater inflater = (LayoutInflater) getSystemService (Context. LAYOUT_INFLATER_SERVICE); LayoutInflater inflater = MainActivity. this. getLayoutInflater ();/* call the inflate (int resource, ViewGroup root) method in the pump. The first parameter is a layout file object. Through this layout file, inflater will plot I in this layout File The second parameter of tems does not need to embed the layout file of the first parameter into another layout file. If you want to write the layout File id, if you do not need to write null */view = inflater. inflate (R. layout. items_layout, null); User u = list. get (position); // obtain the object in the specified data source through the position parameter passed by the callback method // find the control ImageView pic = (ImageView) view in the layout file. findViewById (R. id. items_pic); TextView name = (TextView) view. findViewById (R. id. itmes_name); pic. setImageResource (u. getPic (); // get the Avatar settings from the data source to the ImageView control of the layout file. Name. setText (u. getName (); // obtain the name from the data source and set it to the TextView control of the layout file. Return view ;}}}

 

      

Further steps:

    

 

4. Running result:

        

 

 

  

 

  

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.