先上最后的效果图
定义列表每一行的布局
res / layout / list_view_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 --><ImageViewandroid:id="@+id/img_icon"android:layout_width="64dp"android:layout_height="64dp"android:baselineAlignBottom="true"android:paddingLeft="8dp" /><!-- 定义一个竖直方向的LinearLayout,把QQ呢称与说说的文本框设置出来 --><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid:id="@+id/text_name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:paddingLeft="8dp"android:textColor="#1D1D1C"android:textSize="20sp" /><TextViewandroid:id="@+id/text_msg"android:layout_width="wrap_content"android:layout_height="wrap_content"android:paddingLeft="8px"android:textColor="#B4B4B9"android:textSize="14sp" /></LinearLayout>
</LinearLayout>
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 {@Overrideprotected 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<Map<String,Object>> data = new ArrayList<>();for (int i = 0;i < names.length;i ++){Map<String,Object> map = new HashMap<>();map.put("icon",icons[i]);map.put("name",names[i]);map.put("msg",msgs[i]);data.add(map);}/* from --> todata.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
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity"><ListViewandroid:id="@+id/listV1"android:layout_width="wrap_content"android:layout_height="wrap_content"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintTop_toTopOf="parent"/></androidx.constraintlayout.widget.ConstraintLayout>