以微信首页消息列表为例:
- 中间消息列表中涉及到的数据有:发送人头像、发送人名字、发送内容、发送时间。HomeModel类定义各项数据,及get、set方法:
package com.lala.listviewhome; public class HomeModel { private int picId; private String name; private String time; private String msg; public int getPicId() { return picId; } public void setPicId(int picId) { this.picId = picId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
- 假如接口给的数据如下:
将以上数据赋值给一个泛型为HomeModel的ListInteger PicId[]={R.drawable.itme_icon1,R.drawable.itme_icon2}; String name[] ={"腾讯企业邮箱","微信团队"}; String msg[] ={"腾讯企业邮箱:新邮件通知","欢迎你再次回到微信,如果你在使用过程中有任何问题或建议,记得给我发信反馈哦。"}; String time[] ={"下午14:57","下午14:35"};
List<HomeModel> datas=getDatas();
private List<HomeModel> getDatas() { // TODO Auto-generated method stub List<HomeModel> datas = new ArrayList<HomeModel>();//****** for(int i=0;i<name.length;i++){ datas.add(getModel(i)); } return datas; } private HomeModel getModel(int i) { // TODO Auto-generated method stub HomeModel model =new HomeModel(); model.setPicId(PicId[i]); model.setName(name[i]); model.setMsg(msg[i]); model.setTime(time[i]); return model; }
- 建立适配器HomeListAdapter
package com.lala.listviewhome; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class HomeListAdapter extends BaseAdapter{ private LayoutInflater mInflater; private List<HomeModel> mDatas; public HomeListAdapter( Context context) { // TODO Auto-generated constructor stub mInflater=LayoutInflater.from(context); } public void setAdapterDatas(List<HomeModel> datas){ this.mDatas=datas; } @Override public int getCount() { // TODO Auto-generated method stub return mDatas==null ? 0 : mDatas.size(); } @Override public HomeModel getItem(int position) { // TODO Auto-generated method stub return mDatas.get(position); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view =mInflater.inflate(R.layout.myweixin_list_item, null); ImageView icon=(ImageView)view.findViewById(R.id.item_icon); TextView name=(TextView)view.findViewById(R.id.item_name); TextView time=(TextView)view.findViewById(R.id.item_time); TextView msg=(TextView)view.findViewById(R.id.item_msg); HomeModel model=getItem(position); icon.setImageResource(model.getPicId()); name.setText(model.getName()); time.setText(model.getTime()); msg.setText(model.getMsg()); return view; } }
- 将datas传给适配器,为ListView设置适配器
mAdapter =new HomeListAdapter(this); mAdapter.setAdapterDatas(datas); mListView.setAdapter(mAdapter);
- getView()还要优化!!!