Android 开发即时聊天工具 YQ :(八) 添加/删除好友
国际惯例,先上图:
代码比较简单,只需给listview设置Listener就OK,
当点击删除后,这里没有做提示,会直接删除,删除后应当给服务器发送一个删除好友的包,服务器端更新数据库中的数据。
然后客户端要做的就是更新下好友列表。
具体看代码吧:
1 private void setListViewListener() { 2 listView.setOnItemClickListener(new OnItemClickListener(){ 3 public void onItemClick(AdapterView<?> a, View v, int position,long l) { 4 temp= (BuddyEntity) listView.getItemAtPosition(position); 5 //打开聊天页面 6 Intent intent=new Intent(BuddyActivity.this,ChatActivity.class); 7 intent.putExtra("avatar", temp.getAvatar()); 8 intent.putExtra("account",temp.getAccount()); 9 intent.putExtra("nick", temp.getNick()); 10 startActivity(intent); 11 } 12 }); 13 listView.setOnItemLongClickListener(new OnItemLongClickListener(){ 14 public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int position, long arg3) { 15 temp= (BuddyEntity) listView.getItemAtPosition(position); 16 listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener(){ 17 public void onCreateContextMenu(ContextMenu menu, 18 View arg1, ContextMenuInfo arg2) { 19 menu.setHeaderTitle("操作"); 20 menu.add(0,0,0,"发起会话"); 21 menu.add(0,1,0,"删除好友"); 22 menu.add(0,2,0,"查看好友资料"); 23 } 24 }); 25 return false; 26 } 27 }); 28 } 29 public boolean onContextItemSelected(MenuItem item) { 30 switch(item.getItemId()){ 31 case 0: 32 //打开聊天页面 33 Intent intent=new Intent(BuddyActivity.this,ChatActivity.class); 34 intent.putExtra("avatar", temp.getAvatar()); 35 intent.putExtra("account",temp.getAccount()); 36 intent.putExtra("nick", temp.getNick()); 37 startActivity(intent); 38 break; 39 case 1: 40 //向服务器发送一个删除好友的包 41 SendMessage.sendADbuddy(MoreActivity.me.getAccount(), 42 temp.getAccount(), 43 YQMessageType.DEL_BUDDY); 44 //删除好友列表中的该好友 45 for(int i=0;i<buddyEntityList.size();i++){ 46 if((buddyEntityList.get(i).getAccount())==temp.getAccount()){ 47 buddyEntityList.remove(i); 48 } 49 } 50 listView = (ListView) findViewById(R.id.listview); 51 ba=new BuddyAdapter(this,buddyEntityList); 52 listView.setAdapter(ba); 53 break; 54 case 2: 55 // 56 break; 57 } 58 return super.onContextItemSelected(item); 59 }