歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程:使用ListView實現汽泡短信聊天

Android開發教程:使用ListView實現汽泡短信聊天

日期:2017/3/1 10:41:32   编辑:Linux編程

如這篇文章:http://www.linuxidc.com/Linux/2012-01/50686.htm

我們進行了SimpleAdapter適配器初次嘗試,那麼離實現我們最終想要的效果也不遠啦,只要仿照chata的布局,再編寫第二位聊天人(“路人甲”)的布局chatb——只要讓他靠右顯示就行~。

但是這樣我們每次都要很麻煩的定義一遍SimpleAdapter,為了“偷懶”,我們直接來編寫自己的Adapter,這樣每次定義就方便多了。

先附上最終的代碼:

  1. public void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.main);
  4. chatlist = (ListView) findViewById(R.id.chatlist);
  5. list = new ArrayList<ChatEntity>();
  6. ChatEntity chat1=new ChatEntity("小魏","嗨~",R.layout.chata);
  7. list.add(chat1);
  8. ChatEntity chat2=new ChatEntity("路人甲","你好!",R.layout.chatb);
  9. list.add(chat2);
  10. ChatEntity chat3=new ChatEntity("小魏","我是小魏~",R.layout.chata);
  11. list.add(chat3);
  12. chatlist.setAdapter(new ChatAdapter(TryChatPop2Activity.this,list));
  13. }

如上代碼,在setAdapter時使用了自己的ChatAdapter,以下是類文件代碼:

  1. public class ChatAdapter implements ListAdapter{
  2. private ArrayList<ChatEntity> list;
  3. private Context ctx;
  4. public ChatAdapter(Context context ,ArrayList<ChatEntity> list) {
  5. ctx = context;
  6. this.list = list;
  7. }
  8. public boolean areAllItemsEnabled() {
  9. return false;
  10. }
  11. public boolean isEnabled(int arg0) {
  12. return false;
  13. }
  14. public int getCount() {
  15. return list.size();
  16. }
  17. public Object getItem(int position) {
  18. return list.get(position);
  19. }
  20. public long getItemId(int position) {
  21. return position;
  22. }
  23. public int getItemViewType(int position) {
  24. return position;
  25. }
  26. public View getView(int position, View convertView, ViewGroup parent) {
  27. ChatEntity entity = list.get(position);
  28. int itemLayout = entity.getLayoutID();
  29. LinearLayout layout = new LinearLayout(ctx);
  30. LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  31. vi.inflate(itemLayout, layout,true);
  32. TextView txvName = (TextView) layout.findViewById(R.id.txvName);
  33. txvName.setText(entity.getName());
  34. TextView txvText = (TextView) layout.findViewById(R.id.txvInfo);
  35. txvText.setText(entity.getInfo());
  36. return layout;
  37. }
  38. public int getViewTypeCount() {
  39. return list.size();
  40. }
  41. public boolean hasStableIds() {
  42. return false;
  43. }
  44. public boolean isEmpty() {
  45. return false;
  46. }
  47. public void registerDataSetObserver(DataSetObserver observer) {
  48. }
  49. public void unregisterDataSetObserver(DataSetObserver observer) {
  50. }
  51. }
Copyright © Linux教程網 All Rights Reserved