两种适配器
1.
array_adapter = new ArrayAdapter<String>(context,textViewResourceId,objects);
context 上下文 this
textViewResourceId 当前ListView加载的每一个列表项所对应的布局文件 android.R.layout.simple_list_item_1
objects 数据源 String[]
2.
simple_adapter = new SimpleAdapter(Context,data,resource,from,to);
context 上下文 this
data Map组成的list集合 Map中的键必须包含在from中 数据源
resource 布局文件ID
from Map中的键名
to 绑定数据视图中的ID,与from成对应关系
完整代码
package com.example.bai.my_listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
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 listview;
private ArrayAdapter<String> array_adapter;
//private SimpleAdapter simple_adapter;
private List<Map<String, Object>> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = findViewById(R.id.listView);
//1、新建一个数据适配器
//2、适配器加载数据源
String[] arr_data = {"渗透之C菌","嘻咦啊看","android","java","吾皇","巴扎黑","白茶"};
dataList = new ArrayList<>();
array_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arr_data);
//simple_adapter = new SimpleAdapter(this,getdata(),R.layout.item,new String[]{"pic","text"},new int[]{R.id.pic,R.id.text});
//3、视图加载适配器
listview.setAdapter(array_adapter);
//listview.setAdapter(simple_adapter);
}
private List<Map<String, Object>> getdata(){
for(int i=0;i<20;i++){
Map map= new HashMap<String, Object>();
map.put("pic",R.drawable.ic_launcher_background);
map.put("text","simpleAdapter"+i);
dataList.add(map);
}
return dataList;
}
}
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
android:id="@+id/pic"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="50dp"
android:src="@drawable/ic_launcher_background"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50dp"
android:text="bilibili"/>
</LinearLayout>