本帖最后由 liu 于 2018-12-12 10:57 编辑
SimpleAdapter的使用
SimpleAdapter 简单适配器,可以自定义item布局来显示列表
看一下SimpleAdapter的构造函数:
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
第一个参数是上下文对象
第二个参数是数据源
第三个参数是item的布局
第四个参数是由map中定义的key组成的字符串类型的数组
第五个参数是需要显示的控件id组成的int类型数组
注意:第四个参数和第五个参数必须保证一 一对应
举例:
item_simpleadapter.xml
[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="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="15dp" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:textColor="@android:color/black"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
MainActivity:
[Java] 纯文本查看 复制代码 package com.company.helloworld.firstapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private ImageView mImageView;
private TextView mTextView;
private String[] data = {"开封", "北京", "上海", "广州", "杭州", "苏州"};
private int[] imgs = {R.drawable.sflogo, R.drawable.sflogo, R.drawable.sflogo, R.drawable.sflogo, R.drawable.sflogo, R.drawable.sflogo,};
private HashMap<String, Object> map;
private List<Map<String, Object>> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setData();
initView();
}
//设置数据
private void setData() {
list = new ArrayList<>();
for (int i = 0; i < 6; i++) {
map = new HashMap<>();
map.put("img", imgs[i]);
map.put("name", data[/i][i][i]);
list.add(map);
}
}
private void initView() {
mListView = (ListView) findViewById(R.id.lv);
mImageView = (ImageView) findViewById(R.id.iv);
mTextView = (TextView) findViewById(R.id.tv);
String[] from = {"img", "name"};
int[] to = {R.id.iv, R.id.tv};
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.item_simpleadapter, from, to);
mListView.setAdapter(adapter);
}
}
看一下运行效果:
|