Adapter——SimpleAdapter(搭配ListView)

先上最后的效果图

Adapter——SimpleAdapter(搭配ListView)_第1张图片

定义列表每一行的布局

res / layout / list_view_item.xml




    
    

    
    

        

        

    

MainActivity

package com.clc.app2;

import androidx.appcompat.app.AppCompatActivity;

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

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

public class MainActivity extends AppCompatActivity {

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

        //数据源,数据来源还可以是实体类、资源文件
        int[] icons = {R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher};
        String[] names = {"cpu","内存","显卡","固态硬盘"};
        String[] msgs = {"处理数据","存储进程","图像处理","存储数据"};

        //转化数据的格式(ui要什么格式的数据,这里就转化成什么格式)
        List> data = new ArrayList<>();
        for (int i = 0;i < names.length;i ++){
            Map map = new HashMap<>();
            map.put("icon",icons[i]);
            map.put("name",names[i]);
            map.put("msg",msgs[i]);
            data.add(map);
        }

       /*   from    -->   to
        data.map.key-->R.layout.list_view_item.控件id
        **/
        String[] from = {"icon","name","msg"};
        int[] to = {R.id.img_icon,R.id.text_name,R.id.text_msg};
        BaseAdapter adapter = new SimpleAdapter(this,data,R.layout.list_view_item,from,to);
        ListView listV1 = findViewById(R.id.listV1);
        listV1.setAdapter(adapter);
    }
}

activity_main.xml




    

 

你可能感兴趣的