Android listview, BaseAdapter/ArrayAdapter/SimpleAdapter

1.ListView

ListView is a list display control provided by Android system, which can be used to display our common list forms. Inherited from the abstract class AdapterView. The inheritance diagram is as follows:

 

 

Take wechat friends list for example:

 

Each friend in it is composed of items, and each item exists in the Adapter class (responsible for data processing) and is displayed through ListView

 

2.ListView display principle

The principle of ListView data display is actually MVC design mode, as shown in the following figure:

 

  • Model – a collection of data used to store data organization
  • View – ListView, responsible for data display
  • Controller - manages the Model and sets which specific data to display

 

3. Use BaseAdapter adapter

BaseAdapter is relatively simple. It mainly implements four methods of BaseAdapter by inheriting this class:

public int getCount();
//Set the number of data sets in the adapter( ListView All data rows to display);

public Object getItem(int position):
//Obtain the data items corresponding to the index in the dataset;

public long getItemId(int position);
//Get the corresponding ID,It's usually a direct return position

public View getView(int position,View convertView,ViewGroup parent);
//Get each line Item Display of.
// position:Represents the currently acquired Item What line is it?,Start with 0
// convertView:Reuse of old views,If convertView If it is not empty, it means it can be reused.No need to do it again new One view To use.
// ViewGroup:only LinearLayout perhaps RelativeLayout,If viewGroup Passing in a specific object,So this method creates view Object will be used as this viewGroup Of childView To display.

The example effect is as follows:

 

3.1 write activity main.xml

Just added a ListView:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/lv_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>

</RelativeLayout>

 

4.2 write item.xml

View view used to display each item

<?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:layout_margin="5dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/imageView1"
        android:textSize="20sp"
        android:textColor="#000000"
        android:text="name" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_alignLeft="@+id/tv_name"
        android:text="content"
        android:textColor="#88000000"
        android:textSize="18sp" />

</RelativeLayout>

 

4.3 write MainActivity.java

package com.example.baseadaptertest;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;


class Person {
    String name;
    String content;
    
    public Person(String name,String content){
        this.name = name;
        this.content = content;
    }
    public String getName() {
        return name;
    }
    public String getContent() {
        return content;
    }
}

public class MainActivity extends Activity {
    
    ArrayList<Person>    list;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //1.Add data to display
        list  = new ArrayList<Person>();
        list.add(new Person("Zhang San","18 Year old telephone:158888666"));
        list.add(new Person("Li Si","21 Year old telephone:158888777"));
        list.add(new Person("WangTwo","23 Year old telephone:158888877"));
        list.add(new Person("strategist of the Warring States period","25 Year old telephone:158888997"));
        
        //2.Set up Adapter
        ListView lv_list = (ListView)findViewById(R.id.lv_list);
        lv_list.setAdapter(new MyAdapter());
        
    }
    
    
    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            
            View view = null;
            
            //If convertView If it is empty, the resource view needs to be recreated,If it is not empty, it means it can be reused.No need to do it again new One view To use.
            if(convertView==null){
                 //adopt R.layout.item To create a item View resources
                 view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
            }else{
                
                view = convertView;
            }
            
            //Set what to display
            TextView  tv_name =  (TextView)view.findViewById(R.id.tv_name);
            TextView  tv_content =  (TextView)view.findViewById(R.id.tv_content);
            
            tv_name.setText(list.get(position).getName());
            tv_content.setText(list.get(position).getContent());
            
            
            return view;
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

 

5. Use the ArrayAdapter adapter

ArrayAdapter array adapter is used to bind data with a single format. Only one data of each item needs to be modified. The data source can be a collection or an array

And the ArrayAdapter can be used directly without inheriting this class

There are two common construction methods of ArrayAdapter:

public ArrayAdapter(Context context, int resource, T[] objects);
//First parameter context
//The second parameter contains and has only one textview Layout file for id
//The third parameter shows the data array

public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects);
//First parameter context
//The second parameter can contain a lot of content(ImageView,textview etc.)Layout file for id
//The third parameter points to resource One of the data to be displayed in textView control id
//The third parameter shows the data array

Next, we use the second construction method to demonstrate

The effect is as follows:

 

 

5.1 write activity main.xml

Only a ListView is added, and the content is consistent with the activity main.xml of BaseAdapter

5.2 write item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name"
        android:textColor="#AA000000"
        android:textSize="40sp" />

</LinearLayout>

 

5.3 write MainActivity.java

package com.example.arrayadapter;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //Define a String array
        String[] objects = {"Li Bai","Jiang Ziya","Li Yuan Fang","Gao Jianli","Hou Yi","Wang Zhaojun","Yu Ji"};
        
        //Initialization ArrayAdapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.item, R.id.tv_content, objects);
        
        //Set up ArrayAdapter
        ListView  lv_list = (ListView)findViewById(R.id.lv_list);
        lv_list.setAdapter(adapter);
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

 

 

6. Use SimpleAdapter adapter

The SimpleAdapter adapter is suitable for items with multiple data. Each item is implemented through a Map collection. A Map can contain multiple data

The SimpleAdapter is constructed as follows:

public SimpleAdapter(Context context, List<? extends Map<String, ?>> data,

            int resource, String[] from, int[] to);

//context: context,Fill getApplicationContext()that will do
//data:Contains Map(String ,Object)Of List array,each Map Represent each item Data.
//resource:To load item Of xml Layout file Id
//from:string array, Used to identify a item What needs to be set key.and key Corresponding value Data to display
//to:int array,Fill item xml Control contents to be changed in layout file ID Number ,Used for correspondence from Medium key value,Indicates the set key What control content does the value ultimately change

The effect is as follows:

 

6.1 write activity main.xml

Only a ListView is added, and the content is consistent with the activity main.xml of BaseAdapter

6.2 write item.xml

<?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:layout_margin="5dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/imageView1"
        android:textSize="17sp"
        android:textColor="#000000"
        android:text="name" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_alignLeft="@+id/tv_title"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/tv_title"
        android:text="content"
        android:textColor="#88000000"
        android:textSize="15sp" />

</RelativeLayout>

 

6.3 write MainActivity.java

package com.example.simpleadapter;

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

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        
        
        List<Map<String, String>> data = new ArrayList<Map<String,String>>();
        String[] from = {"title","content"};//Used to identify a item What needs to be set key.and key Corresponding value Data to display,Two are set here key
        int[] to={R.id.tv_title,R.id.tv_content}; //Fill in the content of the control to change ID Number ,Used for correspondence from Two of them key value,
        
        
        //Add content
        Map<String, String>  map1 = new HashMap<String, String>();
        map1.put("title", "Chengdu 5.1 Earthquake magnitude");
        map1.put("content", "Qingbaijiang District 5, Chengdu.1 No casualties were reported in the M S");
        data.add(map1);
        
        Map<String, String>  map2 = new HashMap<String, String>();
        map2.put("title", "Hero League mobile game will be launched soon");
        map2.put("content", "The long-awaited hero League is coming online...");
        data.add(map2);
        
        Map<String, String>  map3 = new HashMap<String, String>();
        map3.put("title", "English Test 4 postponed");
        map3.put("content", "2020 English four eight test postponed...");
        data.add(map3);
        
        Map<String, String>  map4 = new HashMap<String, String>();
        map4.put("title", "Shanghai issues load reduction policy");
        map4.put("content", "Shanghai issues anti epidemic enterprise burden reduction policy for small and medium-sized micro enterprises:Hope to continue to increase...");
        data.add(map4);
        
        Map<String, String>  map5 = new HashMap<String, String>();
        map5.put("title", "Hardcore honey");
        map5.put("content", "The hardest nuclear honey in history!On shoulder 24 RPG Standing in the fire of war...");
        data.add(map5);
        
        //Initialization SimpleAdapter
        SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item, from, to);
        
        
        //Set up SimpleAdapter
        ListView  lv_list = (ListView)findViewById(R.id.lv_list);
        lv_list.setAdapter(adapter);
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

 

 

Ps: if you want to set the Item click event, you can set it by the following method

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

               //Write about what you want to achieve
            }
 });

Tags: Android xml Java encoding

Posted on Tue, 04 Feb 2020 11:41:39 -0500 by Warptweet