[Android] The use of four Adapters

The use of four Adapter


An Adapter is the bridge between the AdapterView view and the data. The Adapter provides access to the data and is also responsible for generating a corresponding View for each item of data.

BaseAdapter

Brief introduction


  • BaseAdapter is the most basic Adapter class, and also the most practical and commonly used class

  • The four basic methods of BaseAdapter
    getCount: the number of items to be bound, such as the number of grids
    getItem: get the object of the position according to an index (location)
    getItemId: get the id of
    the item getView: get the interface to be displayed for the item

Example implementation

We implement a simple product display interface


  • Create the layout of each Item of the ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/good_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="333dp"
        android:layout_marginTop="32dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="92dp"
        android:layout_marginTop="32dp"
        android:text="商品名称:" />

    <TextView
        android:id="@+id/good_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="101dp"
        android:text="商品价格:" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="86dp"
        android:layout_height="86dp"
        tools:srcCompat="@tools:sample/avatars" />
</RelativeLayout>
  • item style
Insert picture description here

Create a Bean to store the display data of each item

package com.example.androidtest.Adapter.BaseAdapter;

public class GoodData {
    private Integer imgId;
    private String good_name;
    private Double good_price;

    public void set(Integer imgId, String good_name, Double good_price) {
        this.imgId = imgId;
        this.good_name = good_name;
        this.good_price = good_price;
    }

    @Override
    public String toString() {
        return "GoodData{" +
                "imgId=" + imgId +
                ", good_name='" + good_name + '\'' +
                ", good_price=" + good_price +
                '}';
    }

    public Integer getImgId() {
        return imgId;
    }

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

    public String getGood_name() {
        return good_name;
    }

    public void setGood_name(String good_name) {
        this.good_name = good_name;
    }

    public Double getGood_price() {
        return good_price;
    }

    public void setGood_price(Double good_price) {
        this.good_price = good_price;
    }
}

Create a class to inherit BaseAdapter and implement several of his methods

package com.example.androidtest.Adapter.BaseAdapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.androidtest.R;

import java.util.List;

public class MyBaseAdapter extends BaseAdapter {
    //创建一个集合来存储数据
    private Context context;
    private List<GoodData> goodDatas;

    public MyBaseAdapter(List<GoodData> goodDatas,Context context) {
        this.goodDatas = goodDatas;
        this.context = context;
    }

    //这个方法返回的是绑定的条目数,在这里也就是数据的数量
    @Override
    public int getCount() {
        return goodDatas.size();
    }

    //获取指定位置的对象
    @Override
    public Object getItem(int position) {
        return goodDatas.get(position);
    }

    //返回指定的id
    @Override
    public long getItemId(int position) {
        return position;
    }

    //在这里将数据和view进行绑定
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //第一个参数是在Activity传过来的context,第二个参数是item的id
        convertView = View.inflate(context, R.layout.activity_base_adapter_test_item,null);
        //将组件一一对应
        ImageView imageView = convertView.findViewById(R.id.good_image);
        TextView good_name = convertView.findViewById(R.id.good_name);
        TextView good_price = convertView.findViewById(R.id.good_price);
        //将数据放入每一个组件
        imageView.setImageResource(goodDatas.get(position).getImgId());
        good_name.setText(goodDatas.get(position).getGood_name());
        good_price.setText(String.valueOf(goodDatas.get(position).getGood_price()));
        return convertView;
    }
}

Create an Activity page and create data in the Activity. Since the Activity interface only needs to create a ListView, it will not be demonstrated here.

package com.example.androidtest.Adapter.BaseAdapter;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

import com.example.androidtest.R;

import java.util.ArrayList;
import java.util.List;

public class BaseAdapterTestActivity extends AppCompatActivity {

    private ListView listView;
    private int [] imgIds = {R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher};
    private String [] goodNames = {"商品1","商品2","商品3","商品4"};
    private double [] goodPrices = {1.11,2.22,3.33,4.44};
    private List<GoodData>goodDatas = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_adapter_test);

        listView = findViewById(R.id.baseAdapterTest);
        //通过循环将数据组装
        for (int i = 0;i<imgIds.length;i++){
            GoodData goodData = new GoodData();
            goodData.set(imgIds[i],goodNames[i],goodPrices[i]);
            goodDatas.add(goodData);
        }
        //实例化BaseAdapter
        MyBaseAdapter adapter = new MyBaseAdapter(goodDatas,getApplicationContext());
        listView.setAdapter(adapter);
    }
}
  • The final result graph
Insert picture description here

SimpleAdapter

Brief introduction


  • This is a simple adapter that can map static data to a view defined in an XML file. You can specify a list of data support such as a Map composed of ArrayList. Each entry in the ArrayList corresponds to a row in the List. Maps contains each row of data. You can specify an XML file that defines the view that is used to display the line, and maps it to the specified view by keyword.
    Parameters of SimpleAdapter

  • SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
    1. context: context.
    2.data: List based on Map. Each item in Data corresponds to each item in ListView. Each item in Data is a Map type, and this Map class contains the data needed for each row of ListView.
    3. resource: it is a layout, which can be referenced by the system or customized.
    4.from: This is an array of names, each name is used to index the Object of Map<String,Object> in each item of the ArrayList array. That is, the key value
    5.to in the map : inside is a TextView array. These TextViews are expressed in the form of id. For example: Android.R.id.text1, this text1 can be indexed in the layout.

Case realization

Show a list of cities with pictures, when you click on a city, the name of the city will be displayed at the top of the list


Create item layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageCity"
        android:layout_width="wrap_content"
        android:layout_height="98dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="17dp"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/nameCity"
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="TextView" />
</RelativeLayout>

The layout is shown as

Insert picture description here

Activity page
Activity page layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Adapter.SimpleAdapter.SimpleAdapterTestActivity">

    <TextView
        android:id="@+id/cityList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp"
        android:text="城市列表" />

    <ListView
        android:id="@+id/simpleAdapter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="3dp"
        android:layout_marginTop="44dp" />
</RelativeLayout>

Activity

package com.example.androidtest.Adapter.SimpleAdapter;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.androidtest.R;

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

public class SimpleAdapterTestActivity extends AppCompatActivity {

    private TextView textView;
    private ListView listView;
    private List<Map<String,Object>>data = new ArrayList<>();
    private String [] cities = {"北京","上海","广东","深圳"};
    private int [] imgs = {R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_adapter_test);

        textView = findViewById(R.id.cityList);
        listView = findViewById(R.id.simpleAdapter);
        //组装数据
        for (int i = 0;i<imgs.length;i++){
            Map<String,Object>map = new HashMap<>();
            map.put("img",imgs[i]);
            map.put("name",cities[i]);
            data.add(map);
        }
        //实例化SimpleAdapter
        SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),data,R.layout.activity_simple_adapter_test_item,new String[]{"img","name"},
        new int[]{R.id.imageCity,R.id.nameCity});
        listView.setAdapter(adapter);
    }
}

result

Insert picture description here

ArrayAdapter

Brief introduction


  • ArrayAdapter is used to bind data in a single format, and the data source can be a collection or an array

  • The
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( ArrayListDemo.this, android.R.layout.simple_list_item_1, adapterData);
    first parameter of ArrayAdapter is the context, the
    second is the id of the item layout file, and the
    third is the data.

Case realization

Activity program contains two, one of which contains a Activity buttons and text boxes, buttons within
the "Please select a degree," click the button to bring up the volume of another Activity, Activity display a list of qualifications, the selection of a degree , The name of the degree will be displayed in the text box of the previous Activity

Since the layout file of this case is relatively simple, it will not be shown here.


The first activity

package com.example.androidtest.Adapter.ArrayAdapter;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.androidtest.R;

import javax.xml.transform.Result;

public class ArrayAdapterFirstActivity extends AppCompatActivity {

    private Button button;
    private TextView textView;

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

        button = findViewById(R.id.arrayAdapterButton);
        textView = findViewById(R.id.arrayAdapterTextView);

        //点击按钮发生跳转
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ArrayAdapterFirstActivity.this, ArrayAdapterSecondActivity.class);
                //由于要接收返回值,故使用这个方法进行跳转
                //但是这样子就要重写onActivityResult
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //必须满足条件,才接收数据
        if (requestCode == 1 && resultCode == RESULT_OK) {
            textView.setText(data.getStringExtra("academic"));
        }
    }
}
  • Since I used startActivityForResult for page jumps, I would rewrite the onActivityResult method

The second activity

package com.example.androidtest.Adapter.ArrayAdapter;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.androidtest.R;

public class ArrayAdapterSecondActivity extends AppCompatActivity {

    private ListView listView;
    private String [] data = {"小学","中学","高职高专","本科","研究生","博士"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_array_adapter_second);

        listView = findViewById(R.id.arrayAdapterListView);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,data);

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ArrayAdapterSecondActivity.this,ArrayAdapterFirstActivity.class);
                String academic = data[position];
                intent.putExtra("academic",academic);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }
}

  • As
    a result, the first page, the
Insert picture description here


second page

Insert picture description here


, and the third page after random selection

Insert picture description here

SimpleCursorAdapter

Brief introduction


The function or purpose of this class is to bind all the columns of a Cursor to ImageView or TextView respectively. You can select the columns you want to display in this Cursor.


  • Parameter introduction
    SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to, int flags)
    context: application context
    layout: the ID of the layout resource file
    c: the cursor of the
    database from: the column name of the
    database to: the column corresponding to the database should correspond to the id of the display View
    flags: flags

The SimpleCursorAdapter parameter from must contain the _id field


Case realization

Created a database named "Books.db", which contains a table: books table, which
stores the basic information of

Insert picture description here


books. Just fill in the book information and
create a book name list interface, and then the user clicks to select the book name, the system opens the book The application of the detailed information interface requires that the book name information be displayed in a list in an activity, and then the detailed information of a certain book is queried and displayed in another activity
The layout file is relatively simple, so I won’t describe it


Customize the DBHelper file to create the table

package com.example.androidtest.Adapter.SimpleCursor;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DBHelper extends SQLiteOpenHelper {
    private int vision = 1;
    private static final String creat_book = "CREATE TABLE books " +
            "(_id INTEGER PRIMARY KEY, " +
            "book_name TEXT, " +
            "book_isbn TEXT, " +
            "book_author TEXT, " +
            "book_press TEXT, " +
            "book_price NUMBERIC " +
            "); ";
    private static final String insert_book1 = "insert into books(book_name, book_isbn, book_author, book_press, book_price) values('Java 程序设计','0001-9999-0001',' 张力',' 电子工业出版社',36.0)";
    private static final String insert_book2 = "insert into books(book_name, book_isbn, book_author, book_press, book_price) values('Android 权威指南','0001-8888-0001',' 王琦',' 人民出版社',59.0)";
    private static final String insert_book3 = "insert into books(book_name, book_isbn, book_author, book_press, book_price) values('SQLite 数据库应用指南','0001-6666-0001',' 李帅',' 希望出版社',28.0)";

    public DBHelper( Context context,  String name,  SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    //在这里创建表,插入数据
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(creat_book);
        db.execSQL(insert_book1);
        db.execSQL(insert_book2);
        db.execSQL(insert_book3);
    }

    //如果数据库的版本发生变化,在这里进行处理
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table books");
        onCreate(db);
    }
}


Create the first page

package com.example.androidtest.Adapter.SimpleCursor;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.example.androidtest.R;

import java.util.HashMap;
import java.util.Map;

public class SimpleCursorFirstActivity extends AppCompatActivity {

    private ListView listView;
    private SQLiteDatabase database;
    private DBHelper dbHelper;
    private Map<String,Integer>map = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_cursor_first);
        listView = findViewById(R.id.simpleCursorListView1);
        //实例化DBHelper
        dbHelper = new DBHelper(getApplicationContext(),"book.db",null,1);
        //得到SQLiteDatabase
        database = dbHelper.getWritableDatabase();
        String [] columns = {"_id","book_name"};
        //执行查询命令,只查询id和name
        Cursor cursor = database.query("books",columns,null,null,null,null,null);
        while (cursor.moveToNext()){
            //将id和name放入map
            map.put(cursor.getString(1),cursor.getInt(0));
        }
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,cursor,new String[]{"book_name"},
                new int[]{android.R.id.text1});
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView)view;
                Intent intent = new Intent(SimpleCursorFirstActivity.this,SimpleCursorSecondActivity.class);
                intent.putExtra("id",String.valueOf(map.get(textView.getText())));
                startActivity(intent);
            }
        });
    }
}

Second page

package com.example.androidtest.Adapter.SimpleCursor;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.androidtest.R;

public class SimpleCursorSecondActivity extends AppCompatActivity {

    private ListView listView;
    private SQLiteDatabase database;
    private DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_cursor_second);
        listView = findViewById(R.id.simpleCursorListView2);
        dbHelper = new DBHelper(getApplicationContext(), "book.db", null, 1);
        database = dbHelper.getWritableDatabase();
        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        String[] columns = {"_id", "book_name", "book_isbn", "book_author", "book_press", "book_price"};
        String[] selectionArgs = {id};
        Cursor cursor = database.query("books", columns, "_id=?", selectionArgs, null, null, null);
        String[] data = new String[6];
        while (cursor.moveToNext()) {
            data[0] = cursor.getString(0);
            data[1] = cursor.getString(1);
            data[2] = cursor.getString(2);
            data[3] = cursor.getString(3);
            data[4] = cursor.getString(4);
            data[5] = cursor.getString(5);
        }
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,data);
        listView.setAdapter(adapter);
    }
}

  • As
    a result, the first page is
Insert picture description here


free to choose one after the second page

Insert picture description here