Android BaseAdapter

ListView and GridView

ListView, list View, is one of the most important components in Android. ListView is used in almost every Android application. Is a list that displays the View view vertically in the project.
GridView
1, Number of columns
android:numColumns="3"
2, Horizontal distance
android:verticalSpacing="10dp"
2, Vertical distance
android:horizontalSpacing="10dp"

Display and caching mechanism

ListView, GridView and other controls can display a large amount of data information. If the ListView has 100 pieces of information, but the screen size is limited, one screen can only display 10 pieces in the following figure. When you slide the ListView upward, item 1 is slid out of the screen area, then the system will recycle item 2 into the Recycler, that is, the View buffer pool, and the item 11 to be displayed will take out the layout file from the buffer pool, reset the data to be displayed by item 11 and put it in the position to be displayed. This is the buffering mechanism of ListView. It is displayed when necessary. After the display, it will be cached.

BaseAdapter

BaseAdapter is a kind of Adapter. In Android, Adapter is an Adapter that can build a bridge between data source and view display, so as to associate and decouple data source and view display.
Inherit this class to implement the four methods of BaseAdapter:

public int getCount(): The number of data sets in the adapter;

public Object getItem(int position): Obtaining the data item corresponding to the index in the data set;

public long getItemId(int position): Gets the corresponding of the specified row ID;

public View getView(int position,View convertView,ViewGroup parent): Get no rows Item Displays the contents of the.

Use demo

Realize simple wechat Homepage

layout

ListView

<?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"
    tools:context="com.qingsu.weixin.WeiXinStart"
    android:orientation="vertical"
    >


    <Toolbar
        android:layout_width="match_parent"
        android:layout_height="40dp"
        >
    <ImageView
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="right"
        android:layout_marginRight="15dp"
        android:background="@mipmap/jia"
        />
    <ImageView
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginRight="15dp"
        android:layout_gravity="right"
        android:background="@mipmap/chaxun"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="24dp"
        android:layout_marginLeft="50dp"
        android:gravity="center"
        android:text="WeChat(999)"
        android:textSize="16sp"
        android:textColor="#000"
        />
    </Toolbar>

    <ListView
        android:id="@+id/lsViewWeiXin"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />


</LinearLayout>

Added entry

<?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="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginLeft="10dp"
            android:orientation="horizontal"
            >

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                >
                <ImageView
                    android:id="@+id/imgAvatar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:src="@mipmap/touxiang0" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="4"
                android:orientation="vertical"
                android:gravity="center_vertical"
                >
                <TextView
                    android:id="@+id/tvUserName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="This is the net name"
                    android:textColor="#000"
                    android:textSize="14sp"
                    />
                <TextView
                    android:id="@+id/tvMsg"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="3dp"
                    android:text="Initial message"
                    android:textSize="10sp"
                    />
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>




create data source

JavaBean s store data

public class ItemBean {
    private String userName;
    private String Msg;
    private int imgId;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getMsg() {
        return Msg;
    }

    public void setMsg(String msg) {
        Msg = msg;
    }

    public int getImgId() {
        return imgId;
    }

    public void setImgId(int imgId) {
        this.imgId = imgId;
    }

    public ItemBean(String userName, String msg, int imgId) {
        this.userName = userName;
        Msg = msg;
        this.imgId = imgId;
    }
    
}

Initialize data source

 ArrayList<ItemBean> list = new ArrayList<ItemBean>();
 ListView listView = findViewById(R.id.lsViewWeiXin);
        int[] imageNmae = {R.mipmap.touxiang0, R.mipmap.touxiang1, R.mipmap.touxiang2, R.mipmap.touxiang3,
                R.mipmap.touxiang4, R.mipmap.touxiang5, R.mipmap.touxiang6, R.mipmap.touxiang7,
                R.mipmap.touxiang8, R.mipmap.touxiang9, R.mipmap.touxiang10, R.mipmap.touxiang11,
                R.mipmap.touxiang12, R.mipmap.touxiang13, R.mipmap.touxiang14, R.mipmap.touxiang15,
                R.mipmap.touxiang16, R.mipmap.touxiang17, R.mipmap.touxiang18, R.mipmap.touxiang19,

        };

        for (int i = 0; i < 19; i++) {
            String userName = "Wechat friends" + i;
            String userMsg = "This is a long voice message. I suggest you delete your friends" + i;
            list.add(new ItemBean(userName, userMsg, imageNmae[i]));
        }

Set stand-alone and long press events for entries

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(WeiXinStart.this, "The first" + position + "Entries were clicked", Toast.LENGTH_SHORT).show();
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(WeiXinStart.this, "The first" + position + "Items were clicked", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

Create BaseAdapter and set cache

The adapter is generally customized in the form of internal classes
Cache mode
Create ViewHolder class and create layout mapping relationship;
Judge convertView. If it is empty, create and set tag. If it is not empty, take out ViewHolder through tag;
Set data for the ViewHolder's control

    class MyAdapter extends BaseAdapter {

  
        @Override
        //The amount of data that the ListView needs to display
        public int getCount() {
            return list.size();
        }

        @Override
        //The data item corresponding to the specified index
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
         //The data item ID corresponding to the specified index
        public long getItemId(int position) {
            return position;
        }

        @Override
        //Returns the display of each item
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = new ViewHolder();

            //If the view has not been instantiated, there is no corresponding cache in the cache pool
            if(convertView == null){
            //Address initialization
                convertView = LayoutInflater.from(WeiXinStart.this).inflate(R.layout.itemweixin_list,null);
                viewHolder.tvName = convertView.findViewById(R.id.tvUserName);
                viewHolder.tvMsg = convertView.findViewById(R.id.tvMsg);
                viewHolder.imgAvatar = convertView.findViewById(R.id.imgAvatar);
                convertView.setTag(viewHolder);//Associating convertView with viewHolder via setTag
            } else {
                //If there is a corresponding view cache in the cache pool, get the viewHolder directly through getTag
                viewHolder = (ViewHolder)convertView.getTag();
            }
            // Fetch bean object
            ItemBean itemBean = list.get(position);
            // Sets the data for the control
            viewHolder.tvName.setText(itemBean.getUserName());
            viewHolder.tvMsg.setText(itemBean.getMsg());
            viewHolder.imgAvatar.setImageResource(itemBean.getImgId());
            return convertView;
        }



        //For caching
        class ViewHolder{
            //Modified components
            TextView tvName,tvMsg;
            ImageView imgAvatar;
        }
    }

Set up adapter

      //Create adapter object
        MyAdapter myAdapter = new MyAdapter();
        //Set up adapter
        listView.setAdapter(myAdapter);

Complete master code

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.qingsu.bean.ItemBean;
import com.qingsu.yingguday05.R;

import java.util.ArrayList;

public class WeiXinStart extends AppCompatActivity {

    ListView listView;
    ArrayList<ItemBean> list = new ArrayList<ItemBean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wei_xin_start);
        myBaseAdapter();
    }

    public  void myBaseAdapter() {
        //Initialization data
        listView = findViewById(R.id.lsViewWeiXin);
        int[] imageNmae = {R.mipmap.touxiang0, R.mipmap.touxiang1, R.mipmap.touxiang2, R.mipmap.touxiang3,
                R.mipmap.touxiang4, R.mipmap.touxiang5, R.mipmap.touxiang6, R.mipmap.touxiang7,
                R.mipmap.touxiang8, R.mipmap.touxiang9, R.mipmap.touxiang10, R.mipmap.touxiang11,
                R.mipmap.touxiang12, R.mipmap.touxiang13, R.mipmap.touxiang14, R.mipmap.touxiang15,
                R.mipmap.touxiang16, R.mipmap.touxiang17, R.mipmap.touxiang18, R.mipmap.touxiang19,

        };

        for (int i = 0; i < 19; i++) {
            String userName = "Wechat friends" + i;
            String userMsg = "This is a long voice message. I suggest you delete your friends" + i;
            list.add(new ItemBean(userName, userMsg, imageNmae[i]));
        }

        //Create adapter object
        MyAdapter myAdapter = new MyAdapter();
        listView.setAdapter(myAdapter);

		//Stand alone event
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(WeiXinStart.this, "The first" + position + "Entries were clicked", Toast.LENGTH_SHORT).show();
            }
        });

		//Long press event
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(WeiXinStart.this, "The first" + position + "Items were clicked", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
    }

    class MyAdapter extends BaseAdapter {

  
        @Override
        //The amount of data that the ListView needs to display
        public int getCount() {
            return list.size();
        }

        @Override
        //The data item corresponding to the specified index
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
         //The data item ID corresponding to the specified index
        public long getItemId(int position) {
            return position;
        }

        @Override
        //Returns the display of each item
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = new ViewHolder();

            //If the view has not been instantiated, there is no corresponding cache in the cache pool
            if(convertView == null){
            //Address initialization
                convertView = LayoutInflater.from(WeiXinStart.this).inflate(R.layout.itemweixin_list,null);
                viewHolder.tvName = convertView.findViewById(R.id.tvUserName);
                viewHolder.tvMsg = convertView.findViewById(R.id.tvMsg);
                viewHolder.imgAvatar = convertView.findViewById(R.id.imgAvatar);
                convertView.setTag(viewHolder);//Associating convertView with viewHolder via setTag
            } else {
                //If there is a corresponding view cache in the cache pool, get the viewHolder directly through getTag
                viewHolder = (ViewHolder)convertView.getTag();
            }
            // Fetch bean object
            ItemBean itemBean = list.get(position);
            // Sets the data for the control
            viewHolder.tvName.setText(itemBean.getUserName());
            viewHolder.tvMsg.setText(itemBean.getMsg());
            viewHolder.imgAvatar.setImageResource(itemBean.getImgId());
            return convertView;
        }



        //For caching
        class ViewHolder{
            //Modified components
            TextView tvName,tvMsg;
            ImageView imgAvatar;
        }
    }



}

demonstration

Keywords: Android

Added by mezise on Wed, 06 Oct 2021 03:58:14 +0300