一,先在布局文件中编写代码
理解SimpleAdapter允许开发者编写自定义的行布局,并且通过键值对把数据映射到控件上。 并且SimpleAdapter适用于简单的图文混搭列表。但不适宜比较复杂的业务逻辑。
1,添加ListView标签,再编写行布局文件,行布局文件就是我们需要写好一个模板比如
这就是一个模板,根据这个模板那么我们最后出现的排列情况就是一样的排列方式。
ListView标签为
activity_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#A39DA3"
android:id="@+id/lv_concact"
android:dividerHeight="1dp"/>
</LinearLayout>
行布局文件为
activity_smple.xml
代码为
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="李白"
android:textSize="35sp"
android:id="@+id/tv_name"
android:layout_marginLeft="15dp"
android:textColor="#0028FF"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="14374959332"
android:layout_marginLeft="20dp"
android:id="@+id/tv_phone"
android:textSize="25sp"/>
</LinearLayout>
二,在Axtivity中编写java代码
2,在Maxtivity中编写代码
步骤在以下代码中
package com.example.mybaseadapter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
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 {
private ListView lvConcact;
// private ListView lvContact;
//
// /***
// * 数据源
// *
// */
// private List<HashMap<String,Object>> users;
// /***
// * 简单适配器
// *
// */
//
// private SimpleAdapter simpleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
//1,获取ListView对象
lvConcact = findViewById(R.id.lv_concact);
//2,准备数据源
List<Map<String,Object>> users = new ArrayList<Map<String, Object>>();
Map<String,Object> map = new HashMap<String, Object>();
map.put("name","王昭君");
map.put("phone","18392746532");
users.add(map);
map = new HashMap<String, Object>();
map.put("name","孙悟空");
map.put("phone","18342746532");
users.add(map);
//,3,配置适配器SimpleAdapter
/**
* this 上下文
* users 数据源
* activity_smple 自定义行布局
* new[] String Map中的keys
* new int[] 行布局中的id keys和id要相对应
* */
SimpleAdapter simpleAdapter = new SimpleAdapter(this,users,R.layout.activity_smple,new String[]{"name","phone"},new int[]{R.id.tv_name,R.id.tv_phone});
//4,将适配器关联到ListView
lvConcact.setAdapter(simpleAdapter);
}
}
最后来看看运行效果