如前文http://blog.csdn.net/xiaowei_cqu/article/details/7045497
我们进行了SimpleAdapter适配器初次尝试,那么离实现我们最终想要的效果也不远啦,只要仿照chata的布局,再编写第二位聊天人(“路人甲”)的布局chatb——只要让他靠右显示就行~。
但是这样我们每次都要很麻烦的定义一遍SimpleAdapter,为了“偷懒”,我们直接来编写自己的Adapter,这样每次定义就方便多了。
先附上最终的代码:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); chatlist = (ListView) findViewById(R.id.chatlist); list = new ArrayList<ChatEntity>(); ChatEntity chat1=new ChatEntity("小魏","嗨~",R.layout.chata); list.add(chat1); ChatEntity chat2=new ChatEntity("路人甲","你好!",R.layout.chatb); list.add(chat2); ChatEntity chat3=new ChatEntity("小魏","我是小魏~",R.layout.chata); list.add(chat3); chatlist.setAdapter(new ChatAdapter(TryChatPop2Activity.this,list)); }
如上代码,在setAdapter时使用了自己的ChatAdapter,以下是类文件代码:
public class ChatAdapter implements ListAdapter{ private ArrayList<ChatEntity> list; private Context ctx; public ChatAdapter(Context context ,ArrayList<ChatEntity> list) { ctx = context; this.list = list; } public boolean areAllItemsEnabled() { return false; } public boolean isEnabled(int arg0) { return false; } public int getCount() { return list.size(); } public Object getItem(int position) { return list.get(position); } public long getItemId(int position) { return position; } public int getItemViewType(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ChatEntity entity = list.get(position); int itemLayout = entity.getLayoutID(); LinearLayout layout = new LinearLayout(ctx); LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); vi.inflate(itemLayout, layout,true); TextView txvName = (TextView) layout.findViewById(R.id.txvName); txvName.setText(entity.getName()); TextView txvText = (TextView) layout.findViewById(R.id.txvInfo); txvText.setText(entity.getInfo()); return layout; } public int getViewTypeCount() { return list.size(); } public boolean hasStableIds() { return false; } public boolean isEmpty() { return false; } public void registerDataSetObserver(DataSetObserver observer) { } public void unregisterDataSetObserver(DataSetObserver observer) { } }
ChatAdapterd的类实现了ListAdapter的接口,并通过ChatEntity中的内容设置了定义布局中聊天对象名字txvName及聊天内容txvInfo的内容,当然你肯定能明白ChatEntity就是存放聊天信息等内容的实体类。
这里我们可以这样写,就是因为ListAdapter的接口是绑定Data和ListView的适配器,实际上我们常用的ArryaAdapter、SimpleAdapter、CursorAdapter就是他的子类。
关系如下:
这样再看代码,甚至再回头看SimpleAdapter就感觉好理解多了,其他内容不细说了,具体参照源码:http://download.csdn.net/detail/xiaowei_cqu/3886321
再上一遍效果图: