Java代码的实现
变量定义
封装,给各个属性设置getter/setter方法
public class ListInfo {
private String title1;
private String title2;
private String title3;
private String title4;
public ListInfo(String title1, String title2, String title3,String title4) {
this.title1=title1;
this.title2=title2;
this.title3=title3;
this.title4=title4;
}
创建Adapter,将数据加载到listview
adapter = new SimpleAdapter(getActivity(),getData(),R.layout.activity_main,new String[]{"title1", "title2", "title3", "title4"}, new int[]{R.id.title1, R.id.title2, R.id.title3, R.id.title4}); ListView listView = (ListView)view.findViewById(R.id.list); listView.setAdapter(adapter);
添加listview的每个item的单击的监听事件
@Override
public void onItemClick(AdapterView> adapterView, View view, int position, long id) {
String data = (String) adapterView.getItemAtPosition(position);
通过Map接口增加数据
private List
// 给list增加数据
HashMap<String, Object> data &#61; new HashMap<>();
// Map映射添加数据 data.put("title1", "蔡志坤"); data.put("title2", "25"); data.put("title3", "ffczk86&#64;gmail.com"); data.put("title4", "厦门市"); // 将map放到list中 datas.add(data); data &#61; new HashMap<>(); data.put("title1", "李杰华"); data.put("title2", "25"); data.put("title3", "aa&#64;bb.com"); data.put("title4", "漳州市"); datas.add(data); data &#61; new HashMap<>(); data.put("title1", "张亮"); data.put("title2", "25"); data.put("title3", "cc&#64;gmail.com"); data.put("title4", "厦门市"); datas.add(data); data &#61; new HashMap<>(); data.put("title1", "刘玄德"); data.put("title2", "25"); data.put("title3", "ffczk86&#64;gmail.com"); data.put("title4", "福州市"); datas.add(data); return datas;
}
}
customerAdapter
public class CustomAdapter extends BaseAdapter {
private List dates;
private Context context;
//通过构造方法获取所需对象&#xff1a;上下文和数据
public CustomAdapter(Context context, List dates) {
this.dates &#61; dates;
this.context &#61; context;
}
&#64;Override
public int getCount() {
return dates.size();
}
&#64;Override
public Object getItem(int i) {
return dates.get(i);
}
&#64;Override
public long getItemId(int i) {
return i;
}
//自定义adapter重写getView&#xff08;&#xff09;方法
&#64;Override
public View getView(int i, View view, ViewGroup parent) {
//1.获取view
if (view &#61;&#61; null) {
view &#61; LayoutInflater.from(context).inflate(R.layout.activity_main, null);
}//2.获取控件对象
TextView title1 &#61; (TextView) view.findViewById(R.id.title1);
TextView title2 &#61; (TextView) view.findViewById(R.id.title2);
TextView title3 &#61; (TextView) view.findViewById(R.id.title3);
TextView title4 &#61; (TextView) view.findViewById(R.id.title4);
//给每个控件赋值
Classinfo classInfo &#61; datas.get(i);
title1.setText(classinfo.gettitle1());
title2.setText(classinfo.getTitle2());
title3.setText(classinfo.gettitle3());
title4.setText(classinfo.gettitle4());
return null;
}