📜  Android中的SimpleAdapter与示例

📅  最后修改于: 2021-05-10 15:48:47             🧑  作者: Mango

在Android中,只要我们想将我们从任何数据源(例如ArrayList,HashMap,SQLite等)获得的某些数据与UI组件(例如ListView,GridView等)绑定在一起,那么适配器就会出现在图片中。基本上,适配器充当UI组件和数据源之间的桥梁。这里简单的适配器是一个类型的适配器。从本质上讲,这是一个简单的适配器,可以将静态数据映射到我们的XML文件(UI组件)中定义的视图,并用于自定义列表或网格项。在这里,我们使用Map的ArrayList(例如,哈希映射,可变映射等)进行数据备份。 ArrayList中的每个条目都对应于列表的一行。映射包含每一行的数据。现在,要显示该行,我们需要一个视图,用于为其指定自定义列表项文件(XML文件)。

SimpleAdapter的常规语法

 

Parameters                                        

DataType

Explanation

context Context When we make an object of SimpleAdapter class  It is used to pass the context ( The reference of current activity). 
data

List>

*** it means a List of Maps whose key‘s type is String and Value can be any datatype.

Each element of the List is different Maps that contain the data of each row and should include all the entries specified in the “from” string array. In our project, we shall use ArrayList.
resource

 int

***Integer Datatype

This parameter is used to pass the resource id of the layout ( XML file ) which should contain the different views of each row of the list. The layout file should include at least those named views defined in “to”.
from An array of String type A list of column names that will be added to the Map associated with each item. In this array, there should be a column name for each item (Views) of each row of the list.
to An array of int type. This array parameter stores the ids of different views that should display the column in the “from” parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the “from” parameter.

例子

下面给出了一个示例图像,以使您对本文中要做的事情有一个了解在这个项目中,我们将使这个应用程序具有一些水果的列表,并且在列表的每一行中都有一个水果图像和名称。请注意,我们将使用KotlinJava语言来实现相同的项目。现在,选择您喜欢的语言。

Android中的SimpleAdapter与示例

分步实施

步骤1:创建一个新项目

打开Android Studio>创建新项目>选择一个空活动>提供一个项目名称(此处的项目名称为“ GFG_SimpleAdapter ”)。

步骤2:使用activity_main.xml文件

activity_main.xml文件中,在RelativeLayout内部创建一个ListView。以下是activity_main.xml文件的代码。

XML


     
    
    
 


XML


     
    
    
     
    
    
     


Java
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
 
public class MainActivity extends AppCompatActivity {
 
    ListView listView;
 
    // creating  a String type array (fruitNames)
    // which contains names of different fruits' images
    String fruitNames[] = {"Banana", "Grape", "Guava", "Mango", "Orange", "Watermelon"};
 
    // creating an Integer type array (fruitImageIds) which
    // contains IDs of different fruits' images
    int fruitImageIds[] = {R.drawable.banana,
            R.drawable.grape,
            R.drawable.guava,
            R.drawable.mango,
            R.drawable.orange,
            R.drawable.watermelon};
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Binding the ListView  of activity_main.xml file
        // with this java code in MainActivity.java
        listView = findViewById(R.id.listView);
 
        // creating an ArrayList of HashMap.The kEY of the HashMap
        // is a String and VALUE is of any datatype(Object)
        ArrayList> list = new ArrayList<>();
 
        // By a for loop, entering different types of data in HashMap,
        // and adding this map including it's datas into the ArrayList
        // as list item and this list is the second parameter of the SimpleAdapter
        for (int i = 0; i < fruitNames.length; i++) {
 
            // creating an Object of HashMap class
            HashMap map = new HashMap<>();
 
            // Data entry in HashMap
            map.put("fruitName", fruitNames[i]);
            map.put("fruitImage", fruitImageIds[i]);
 
            // adding the HashMap to the ArrayList
            list.add(map);
        }
 
        // creating A string type array(from) which contains
        // column names for each View in each row of the list
        // and this array(form) is the fourth parameter of the SimpleAdapter
        String[] from = {"fruitName", "fruitImage"};
 
        // creating an integer type array(to) which contains
        // id of each View in each row of the list
        // and this array(form) is the fifth parameter of the SimpleAdapter
        int to[] = {R.id.textView, R.id.imageView};
 
        // creating an Object of SimpleAdapter class and
        // passing all the required parameters
        SimpleAdapter simpleAdapter = new SimpleAdapter(getApplicationContext(), list, R.layout.list_row_items, from, to);
 
        // now setting the simpleAdapter to the ListView
        listView.setAdapter(simpleAdapter);
    }
}


Kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ListView
import android.widget.SimpleAdapter
import java.util.ArrayList
import java.util.HashMap
 
class MainActivity : AppCompatActivity() {
   
    private lateinit var listView:ListView
   
    // creating  a String type array
      // (fruitNames) which contains
    // names of different fruits' images
    private val fruitNames=arrayOf("Banana","Grape","Guava","Mango","Orange","Watermelon")
     
    // creating an Integer type array (fruitImageIds) which
    // contains IDs of different fruits' images
    private val fruitImageIds=arrayOf(R.drawable.banana,
                              R.drawable.grape,
                              R.drawable.guava,
                              R.drawable.mango,
                              R.drawable.orange,
                              R.drawable.watermelon) 
     
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // ViewBinding the ListView  of activity_main.xml file
        // with this kotlin code in MainActivity.kt
        listView=findViewById(R.id.listView)
         
        // creating an ArrayList of HashMap.The kEY of the HashMap is
        // a String and VALUE is of any datatype(Any)
        val list=ArrayList>()
         
        // By a for loop, entering different types of data in HashMap,
        // and adding this map including it's datas into the ArrayList
        // as list item and this list is the second parameter of the SimpleAdapter
        for(i in fruitNames.indices){
            val map=HashMap()
             
            // Data entry in HashMap
            map["fruitName"] = fruitNames[i]
            map["fruitImage"]=fruitImageIds[i]
           
            // adding the HashMap to the ArrayList
            list.add(map)
        }
         
        // creating A string type array(from) which contains
        // column names for each View in each row of the list
        // and this array(form) is the fourth parameter of the SimpleAdapter
        val from=arrayOf("fruitName","fruitImage")
         
        // creating an integer type array(to) which contains
        id of each View in each row of the list
        and this array(form) is the fifth parameter of the SimpleAdapter*/
         
        val to= intArrayOf(R.id.textView,R.id.imageView)
         
        // creating an Object of SimpleAdapter
          // class and passing
        // all the required parameters
        val simpleAdapter=SimpleAdapter(this,list,R.layout.list_row_items,from,to)
         
        // now setting the simpleAdapter
          // to the ListView
        listView.adapter = simpleAdapter
    }
}


activity_main.xml接口:

步骤3:创建另一个XML文件(名为list_row_items),并为ListView的每一行创建UI

创建一个新的布局资源文件,并将其命名为list_row_items

以下是list_row_items.xml文件的代码。

XML格式



     
    
    
     
    
    
     

list_row_items.xml接口:

步骤4:使用MainActivity文件

在这里,我们将向您展示如何在Java和Kotlin中实现SimpleAdapter。现在,您选择自己喜欢的一个。下面是MainActivity文件的代码。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
 
public class MainActivity extends AppCompatActivity {
 
    ListView listView;
 
    // creating  a String type array (fruitNames)
    // which contains names of different fruits' images
    String fruitNames[] = {"Banana", "Grape", "Guava", "Mango", "Orange", "Watermelon"};
 
    // creating an Integer type array (fruitImageIds) which
    // contains IDs of different fruits' images
    int fruitImageIds[] = {R.drawable.banana,
            R.drawable.grape,
            R.drawable.guava,
            R.drawable.mango,
            R.drawable.orange,
            R.drawable.watermelon};
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Binding the ListView  of activity_main.xml file
        // with this java code in MainActivity.java
        listView = findViewById(R.id.listView);
 
        // creating an ArrayList of HashMap.The kEY of the HashMap
        // is a String and VALUE is of any datatype(Object)
        ArrayList> list = new ArrayList<>();
 
        // By a for loop, entering different types of data in HashMap,
        // and adding this map including it's datas into the ArrayList
        // as list item and this list is the second parameter of the SimpleAdapter
        for (int i = 0; i < fruitNames.length; i++) {
 
            // creating an Object of HashMap class
            HashMap map = new HashMap<>();
 
            // Data entry in HashMap
            map.put("fruitName", fruitNames[i]);
            map.put("fruitImage", fruitImageIds[i]);
 
            // adding the HashMap to the ArrayList
            list.add(map);
        }
 
        // creating A string type array(from) which contains
        // column names for each View in each row of the list
        // and this array(form) is the fourth parameter of the SimpleAdapter
        String[] from = {"fruitName", "fruitImage"};
 
        // creating an integer type array(to) which contains
        // id of each View in each row of the list
        // and this array(form) is the fifth parameter of the SimpleAdapter
        int to[] = {R.id.textView, R.id.imageView};
 
        // creating an Object of SimpleAdapter class and
        // passing all the required parameters
        SimpleAdapter simpleAdapter = new SimpleAdapter(getApplicationContext(), list, R.layout.list_row_items, from, to);
 
        // now setting the simpleAdapter to the ListView
        listView.setAdapter(simpleAdapter);
    }
}

科特林

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ListView
import android.widget.SimpleAdapter
import java.util.ArrayList
import java.util.HashMap
 
class MainActivity : AppCompatActivity() {
   
    private lateinit var listView:ListView
   
    // creating  a String type array
      // (fruitNames) which contains
    // names of different fruits' images
    private val fruitNames=arrayOf("Banana","Grape","Guava","Mango","Orange","Watermelon")
     
    // creating an Integer type array (fruitImageIds) which
    // contains IDs of different fruits' images
    private val fruitImageIds=arrayOf(R.drawable.banana,
                              R.drawable.grape,
                              R.drawable.guava,
                              R.drawable.mango,
                              R.drawable.orange,
                              R.drawable.watermelon) 
     
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // ViewBinding the ListView  of activity_main.xml file
        // with this kotlin code in MainActivity.kt
        listView=findViewById(R.id.listView)
         
        // creating an ArrayList of HashMap.The kEY of the HashMap is
        // a String and VALUE is of any datatype(Any)
        val list=ArrayList>()
         
        // By a for loop, entering different types of data in HashMap,
        // and adding this map including it's datas into the ArrayList
        // as list item and this list is the second parameter of the SimpleAdapter
        for(i in fruitNames.indices){
            val map=HashMap()
             
            // Data entry in HashMap
            map["fruitName"] = fruitNames[i]
            map["fruitImage"]=fruitImageIds[i]
           
            // adding the HashMap to the ArrayList
            list.add(map)
        }
         
        // creating A string type array(from) which contains
        // column names for each View in each row of the list
        // and this array(form) is the fourth parameter of the SimpleAdapter
        val from=arrayOf("fruitName","fruitImage")
         
        // creating an integer type array(to) which contains
        id of each View in each row of the list
        and this array(form) is the fifth parameter of the SimpleAdapter*/
         
        val to= intArrayOf(R.id.textView,R.id.imageView)
         
        // creating an Object of SimpleAdapter
          // class and passing
        // all the required parameters
        val simpleAdapter=SimpleAdapter(this,list,R.layout.list_row_items,from,to)
         
        // now setting the simpleAdapter
          // to the ListView
        listView.adapter = simpleAdapter
    }
}

输出: