消息列表android
2018-05-02 18:43:34 a1527238987 阅读数 1168

1.自上而下显示;

listview添加属性

 android:stackFromBottom="true"//true 定位到底部
 android:transcriptMode="alwaysScroll"//自动滚动定位到新增位置

数据更新:list.addAll( list1);

2.自下而上显示:

listview添加属性

 android:stackFromBottom="false"
 android:transcriptMode="normal"//

数据更新:

 Collections.reverse(list1);//将新数据逆转、再添加到头部

list.addAll( 0,list1);//在顶部添加数据





2017-04-19 21:40:34 Julse 阅读数 314

消息列表布局

实现效果:

simpleAdapter实现消息列表

weixin.xml布局视图:

simpleAdapter实现消息列表

outline视图:

simpleAdapter实现消息列表

源码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/image_head"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="10px"

        android:src="@drawable/head3" />

    <TextView
        android:id="@+id/textNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/image_head"
        android:text="张三"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/text_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/image_head"
        android:layout_alignLeft="@+id/textNo"
        android:text="偷得浮生半日闲" />

    <TextView
        android:id="@+id/text_sent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="15:40" />

</RelativeLayout>

Activity:

package com.julse.adapter;
/**
 * 列表的使用方法
 * 设置界面
 */
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.location.GpsStatus.Listener;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class SettingActivity extends Activity {
    private ListView lv;
//  strSettingsStrings:6
    private String[] strSettingsStrings={"新消息提醒","勿扰模式","聊天","隐私","通用","账号与安全"};
//  name:5
    private String[] name={"张三","李四","王二","麻子","赵五"};
//  images:5
    private int[] images={R.drawable.head1,R.drawable.head2,R.drawable.head3,R.drawable.head4,R.drawable.head5};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        setTitle("联系人列表");
        lv=(ListView) findViewById(R.id.listView1);
//      方法一:实现最简单的adapter
        /*ArrayAdapter adapter= new ArrayAdapter(SettingActivity.this, 
                android.R.layout.simple_list_item_1,
                strSettingsStrings);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
//              arg2是点击的项id
                Toast.makeText(SettingActivity.this,strSettingsStrings[arg2]+" arg2="+arg2, Toast.LENGTH_LONG).show();
            }
        });
        lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                Toast.makeText(SettingActivity.this,strSettingsStrings[arg2]+" arg2="+arg2+"长按", Toast.LENGTH_LONG).show();
                return false;
            }
        });*/

//      方法二:设置文字组
        /*ArrayList arrayList= new ArrayList();
        for (int i = 0; i < strSettingsStrings.length; i++) {
            HashMap map=new HashMap();
            map.put("content", strSettingsStrings[i]);
            map.put("state", "否");
            arrayList.add(map);

        }
        SimpleAdapter simple= new SimpleAdapter(SettingActivity.this, 
                arrayList, R.layout.item_listview, 
                new String[]{"content","state"}, 
                new int[]{R.id.textView1,R.id.textView2});
        lv.setAdapter(simple);
    }*/
//      方法三:既有图片又有文字

        ArrayList arrayList2=new ArrayList();
/*      SimpleDateFormat formatter    =   new    SimpleDateFormat    ("yyyy年MM月dd日    HH:mm:ss     ");       
        Date curDate    =   new    Date(System.currentTimeMillis());//获取当前时间       
        String    str    =    formatter.format(curDate);  */

        SimpleDateFormat time_format=new SimpleDateFormat("HH:mm");
        for (int i = 0; i < name.length; i++) {
            Date date=new Date(System.currentTimeMillis());
            String nowTime=time_format.format(date);
            HashMap map=new HashMap();
            map.put("head",images[i]);
            map.put("name", name[i]);
            map.put("time", nowTime);
            map.put("signal", strSettingsStrings[i]);
            arrayList2.add(map);
        }
        SimpleAdapter simples=new SimpleAdapter(
                SettingActivity.this,
                arrayList2,
                R.layout.weixin,
                new String[]{"head","name","time","signal"},
                new int[]{R.id.image_head,R.id.textNo,R.id.text_sent,R.id.text_content});
        lv.setAdapter(simples);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.setting, menu);
        return true;
    }

}
2014-02-11 19:36:18 FX_SKY 阅读数 5305

之前一篇文章中介绍了微信滑动删除效果(Android 仿微信对话列表滑动删除效果),这一篇在其基础上实现QQ消息列表ListView滑动删除效果,大致原理差不多,这里就不细说了。


运行效果如下:









SwipeListView.java

package com.example.swipelistview.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.example.swipelistview.R;

public class SwipeListView extends ListView {

	private static final String TAG = SwipeListView.class.getSimpleName();

	private boolean isShown;

	private View mPreItemView;

	private View mCurrentItemView;

	private float mFirstX;

	private float mFirstY;

	private boolean mIsHorizontal;

	public SwipeListView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public SwipeListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public SwipeListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		float lastX = ev.getX();
		float lastY = ev.getY();
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:

			mIsHorizontal = false;
			
			mFirstX = lastX;
			mFirstY = lastY;
			int motionPosition = pointToPosition((int) mFirstX, (int) mFirstY);

			Log.e(TAG, "onInterceptTouchEvent----->ACTION_DOWN position=" + motionPosition);
			
			if (motionPosition >= 0) {
				View currentItemView = getChildAt(motionPosition - getFirstVisiblePosition());
				mPreItemView = mCurrentItemView;
				mCurrentItemView = currentItemView;
			}
			break;

		case MotionEvent.ACTION_MOVE:
			float dx = lastX - mFirstX;
			float dy = lastY - mFirstY;

			if (Math.abs(dx) >= 5 && Math.abs(dy) >= 5) {
				return true;
			}
			break;

		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:

			Log.i(TAG, "onInterceptTouchEvent----->ACTION_UP");
			if (isShown && mPreItemView != mCurrentItemView) {
				Log.i(TAG, "1---> hiddenRight");
				/**
                 * 情况一:
                 * <p>
                 * 一个Item的右边布局已经显示,
                 * <p>
                 * 这时候点击任意一个item, 那么那个右边布局显示的item隐藏其右边布局
                 */
				hiddenRight(mPreItemView);
			}
			break;
		}

		return super.onInterceptTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		float lastX = ev.getX();
		float lastY = ev.getY();

		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.i(TAG, "---->ACTION_DOWN");
			break;

		case MotionEvent.ACTION_MOVE:
			float dx = lastX - mFirstX;
			float dy = lastY - mFirstY;

			mIsHorizontal = isHorizontalDirectionScroll(dx, dy);
			
			if (!mIsHorizontal) {
				break;
			}

			Log.i(TAG, "onTouchEvent ACTION_MOVE");
			
			if (mIsHorizontal) {
                if (isShown && mPreItemView != mCurrentItemView) {
                	Log.i(TAG, "2---> hiddenRight");
                    /**
                     * 情况二:
                     * <p>
                     * 一个Item的右边布局已经显示,
                     * <p>
                     * 这时候左右滑动另外一个item,那个右边布局显示的item隐藏其右边布局
                     * <p>
                     * 向左滑动只触发该情况,向右滑动还会触发情况五
                     */
                    hiddenRight(mPreItemView);
                }
			}else {
                if (isShown) {
                	Log.i(TAG, "3---> hiddenRight");
                    /**
                     * 情况三:
                     * <p>
                     * 一个Item的右边布局已经显示,
                     * <p>
                     * 这时候上下滚动ListView,那么那个右边布局显示的item隐藏其右边布局
                     */
                    hiddenRight(mPreItemView);
                }
            }
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			Log.i(TAG, "============ACTION_UP");
			if (isShown) {
				Log.i(TAG, "4---> hiddenRight");
                /**
                 * 情况四:
                 * <p>
                 * 一个Item的右边布局已经显示,
                 * <p>
                 * 这时候左右滑动当前一个item,那个右边布局显示的item隐藏其右边布局
                 */
                hiddenRight(mPreItemView);
            }

            if (mIsHorizontal) {
                if (mFirstX - lastX > 30) {
                    showRight(mCurrentItemView);
                } else {
                	Log.i(TAG, "5---> hiddenRight");
                    /**
                     * 情况五:
                     * <p>
                     * 向右滑动一个item,且滑动的距离超过了右边View的宽度的一半,隐藏之。
                     */
                    hiddenRight(mCurrentItemView);
                }
                return true;
            }
			break;
		}

		return super.onTouchEvent(ev);
	}

	private void showRight(View rightView) {
		RelativeLayout rl_right=(RelativeLayout)rightView.findViewById(R.id.item_right);
		rl_right.setVisibility(View.VISIBLE);
		
		isShown = true;
	}
	
	private void hiddenRight(View rightView) {
		
		RelativeLayout rl_right=(RelativeLayout)rightView.findViewById(R.id.item_right);
		rl_right.setVisibility(View.GONE);
		
		isShown = false;
	}

	/**
	 * @param dx
	 * @param dy
	 * @return judge if can judge scroll direction
	 */
	private boolean isHorizontalDirectionScroll(float dx, float dy) {
		boolean mIsHorizontal = true;

		if (Math.abs(dx) > 30 && Math.abs(dx) > 2 * Math.abs(dy)) {
			mIsHorizontal = true;
			System.out.println("mIsHorizontal---->" + mIsHorizontal);
		} else if (Math.abs(dy) > 30 && Math.abs(dy) > 2 * Math.abs(dx)) {
			mIsHorizontal = false;
			System.out.println("mIsHorizontal---->" + mIsHorizontal);
		}

		return mIsHorizontal;
	}
	
}


SwipeAdapter.java

package com.example.swipelistview.adapter;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.swipelistview.R;
import com.example.swipelistview.entity.WXMessage;

public class SwipeAdapter extends BaseAdapter {
    /**
     * 上下文对象
     */
    private Context mContext = null;
    private List<WXMessage> data;
    
    /**
     * @param mainActivity
     */
    public SwipeAdapter(Context ctx,List<WXMessage> data) {
        mContext = ctx;
        this.data = data;
    }

    @Override
    public int getCount() {
//      return 100;
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
    	
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
            holder = new ViewHolder();
            holder.item_left = (RelativeLayout)convertView.findViewById(R.id.item_left);
            holder.item_right = (RelativeLayout)convertView.findViewById(R.id.item_right);
            
            holder.iv_icon = (ImageView) convertView.findViewById(R.id.iv_icon);
            holder.tv_title = (TextView)convertView.findViewById(R.id.tv_title);
            holder.tv_msg = (TextView)convertView.findViewById(R.id.tv_msg);
            holder.tv_time = (TextView)convertView.findViewById(R.id.tv_time);
            
            holder.item_right_txt = (TextView)convertView.findViewById(R.id.item_right_txt);
            convertView.setTag(holder);
        } else {// 有直接获得ViewHolder
            holder = (ViewHolder)convertView.getTag();
        }
        
        Log.i("SwipeAdapter", "getView position="+position);
        
        WXMessage msg = data.get(position);
        
        holder.tv_title.setText(msg.getTitle());
        holder.tv_msg.setText(msg.getMsg());
        holder.tv_time.setText(msg.getTime());
        
        holder.iv_icon.setImageResource(msg.getIcon_id());
        
        holder.item_right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onRightItemClick(v, position);
                }
            }
        });
        return convertView;
    }

    static class ViewHolder {
    	RelativeLayout item_left;
    	RelativeLayout item_right;

        TextView tv_title;
        TextView tv_msg;
        TextView tv_time;
        ImageView iv_icon;

        TextView item_right_txt;
    }
    
    /**
     * 单击事件监听器
     */
    private onRightItemClickListener mListener = null;
    
    public void setOnRightItemClickListener(onRightItemClickListener listener){
    	mListener = listener;
    }

    public interface onRightItemClickListener {
        void onRightItemClick(View v, int position);
    }
}




Demo下载地址:http://download.csdn.net/detail/fx_sky/6913747





2017-07-12 09:34:44 m0_37361593 阅读数 7377

使用拓展消息实现聊天界面和消息列表的头像和昵称的展示

上篇文章只是简单的介绍怎么集成环信,但是在自己的项目中涉及到聊天这一块。在做android开发的时候,往往要考虑到怎么展示用户昵称和头像的问题。说明一点:我们这个项目的用户头像和昵称是我们后台返回给我们的。我们只需要给用户设置拓展属性。

一、首先集成环信:

app如何引入一个module作为依赖:

  1. 在自己的该app工作空间下,导入easeui这个module

  2. 在项目菜单的project structure中,app---dependencies--添加module依赖。

  3. clean工程—rebuild工程。


首先要解决架包冲突问题。(v7冲突。)

解决方案:1.app下的架包放到easeUIgradle中。

2.实在不行,就查看所有gradle下面时候有重复的架包及依赖。


二、集成环信的聊天界面:

由于要使用到拓展消息,所以我们首先在工具类中定义一下我们自己和好友的属性。from表示我,to表示好友。

        public static final String FROM_AVATER="from_avater";
	public static final String FROM_NICHENG="from_nicheng";
	public static final String TO_AVATER="to_avater";
	public static final String TO_NICHENG="to_nicheng";

在easeui的widget包下的chatrow包的EaseChatRow这个类中,在消息的发送和接收处将其更改为拓展属性:

/**
 * 聊天界面
 * 聊天界面需要获取用户的头像和昵称
 * 方法:采用扩展属性的方法。
 * 定义 自己和他人的属性:from_avater from_nicheng自己的头像和昵称   
 * to_avater  to_nicheng 对方的头像和昵称
 * 自身头像昵称在进入应用的时候存到文件中,待聊天界面直接从文件中取出来。
 * 对方头像从消息列表中获取
 */
//环信中的聊天页面
//set nickname and avatar
        /**
         * 聊天页面
         */
        if (message.direct() == Direct.SEND) {
            //  EaseUserUtils.setUserAvatar(context, EMClient.getInstance().getCurrentUser(), userAvatarView);
            try {
                Glide.with(getContext()).load(message.getStringAttribute("from_avater")).into(userAvatarView);
             //   usernickView.setText(message.getStringAttribute("from_nicheng"));
                EaseUserUtils.setUserNick(message.getStringAttribute("from_nicheng"), usernickView);
                
            } catch (HyphenateException e) {

            }
        }
        //   
        else {
            //  EaseUserUtils.setUserAvatar(context, message.getFrom(), userAvatarView);
            //  EaseUserUtils.setUserNick(message.getFrom(), usernickView);
            try {
              //  usernickView.setText(message.getStringAttribute("from_nicheng"));
               EaseUserUtils.setUserNick(message.getStringAttribute("from_nicheng"), usernickView);
                Glide.with(getContext()).load(message.getStringAttribute("from_avater")).into(userAvatarView);
            } catch (HyphenateException e) {

            }
        }

在自己的app下定义聊天界面ChatActivity如下:

public class ChatActivity extends BaseActivity {
    private String logo;
    private static String name;
    private String logoPath;
    private String tradeName;
    public static ChatActivity activityInstance;
    private Bundle extras;

    //给扩展属性设置头像和昵称。
    EaseChatFragment.EaseChatFragmentHelper helper = new EaseChatFragment.EaseChatFragmentHelper() {
        @Override
        public void onSetMessageAttributes(EMMessage message) {
            // 附带扩展属性,头像和昵称他人的
            message.setAttribute(Utils.TO_AVATER, logo);
            message.setAttribute(Utils.TO_NICHENG, name);
          
            //我的头像  存到自己的文件中
            message.setAttribute(Utils.FROM_AVATER, logoPath);
            message.setAttribute(Utils.FROM_NICHENG, tradeName);
        }
        @Override
        public void onEnterToChatDetails() {
        }
        @Override
        public void onAvatarClick(String username) {
        }
        @Override
        public void onAvatarLongClick(String username) {
        }
        @Override
        public boolean onMessageBubbleClick(EMMessage message) {
            return false;
        }
        @Override
        public void onMessageBubbleLongClick(EMMessage message) {
        }
        @Override
        public boolean onExtendMenuItemClick(int itemId, View view) {
            return false;
        }
        @Override
        public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
            return null;
        }
    };
    
    @Override
    protected void init() {
        super.init();
        //在布局中设置一个容器。集成环信的聊天界面添加进去
        setContentView(R.layout.activity_chat);
        initView();
    }
    private void initView() {
        //从消息列表获取头像和昵称
        logo = getIntent().getStringExtra(Utils.FROM_AVATER);
        name = getIntent().getStringExtra(Utils.FROM_NICHENG);
        //并从本地取出我的头像
        logoPath = SpUtils.getLogoPath(this);
        tradeName = SpUtils.getTradeName(this);
        //将环信的聊天界面chatFragment集成进来
        initHx();
    }
    public void initHx() {
        activityInstance = this;
        ChatFragment chatf = new ChatFragment();
        //获取从上个界面获取的参数,传给聊天界面。
        extras = getIntent().getExtras();
        chatf.setArguments(extras);
        //这个监听是接收到消息就给消息设置拓展属性。
        chatf.setChatFragmentListener(helper);
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatf).commit();

    }

    /**
     * 继承环信的聊天页面  
     * 实现消息监听和聊天页面的标题上显示的对方昵称
     * 
     *
     */
    public static class ChatFragment extends EaseChatFragment implements EMMessageListener {
        /**
         * 设置聊天页面的title上面的昵称
         */
        @Override
        protected void setUpView() {
            super.setUpView();
            titleBar.setTitle(name);
            
        }

    }

}

当我们点击好友列表时(我的好友列表的数据是从服务器获取的。能够获取到好友的头像和昵称。自己的头像和昵称已进入自己的应用就保存到自己的文件中):

//则点击进入聊天界面,和环信id

//从服务器获取到昵称头像
                    String chatId = data.getChatId();
                    String name = data.getName();
                    String headerURL = data.getHeaderURL();


                    Log.i("shi",chatId+"#"+name+"#"+headerURL);
                    Intent intent = new Intent(this, ChatActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(EaseConstant.EXTRA_USER_ID, chatId);  //传递用户id
                    bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE); //传递是群聊还是单聊
                    intent.putExtras(bundle);
                    intent.putExtra(Utils.FROM_NICHENG, name);
                    intent.putExtra(Utils.FROM_AVATER, headerURL);
                    startActivity(intent);

三、集成环信的消息列表:

在easeui中找到EaseConversationAdapter这个类。当接收到最后一条消息的时候将其设置为对应的拓展属性。(这样在展示消息列表时会展示好友的头像昵称)

 else if(conversation.getType() == EMConversationType.ChatRoom){
            holder.avatar.setImageResource(R.drawable.ease_group_icon);
            EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(username);
            holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
            holder.motioned.setVisibility(View.GONE);
        }else {/**
         * 获取列表最后一条消息是接收还是发送
         * 然后设置昵称和头像
         */
            EMMessage lastMessage = conversation.getLastMessage();
            if (lastMessage.direct() == EMMessage.Direct.RECEIVE) {
                try {
                    Glide.with(getContext()).load(lastMessage.getStringAttribute("from_avater")).into(holder.avatar);
                    EaseUserUtils.setUserNick(lastMessage.getStringAttribute("from_nicheng"), holder.name);
                } catch (HyphenateException e) {
                }
            } else {
                try {
                    EaseUserUtils.setUserNick(lastMessage.getStringAttribute("to_nicheng"), holder.name);
                    Glide.with(getContext()).load(lastMessage.getStringAttribute("to_avater")).into(holder.avatar);
                } catch (HyphenateException e) {
                }
            }
        }
        {
            // EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
            // EaseUserUtils.setUserNick(username, holder.name);
            holder.motioned.setVisibility(View.GONE);
        }

在app项目中集成环信的消息列表:

1.	写一个布局文件,布局文件中设置一个容器,用来接收 环信的消息列表。
EaseConversationListFragment  cf = new EaseConversationListFragment();
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.fl_contains,cf).commit();
2.	给消息列表设置一个消息到来的监听。
MClient.getInstance().chatManager().addMessageListener(emMessageListener);
private EMMessageListener emMessageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> list) {
            //在环信包下的消息列表中对消息对象进行了筛选。将第0个消息存为32个8账号的消息,
            // 从消息列表中取出第0个消息对象。(第0个消息就是存有32个8该账号的消息对象)
            EMMessage emMessage = list.get(0);
            String s = emMessage.getBody().toString();
            try {
                //这里是订单消息
                EMConversation conversation = EMClient.getInstance().chatManager().getConversation("88888888888888888888888888888888");
                //未读的消息数量普通消息
                unreadMsgCount = conversation.getUnreadMsgCount();
                Log.i("123---", s + "---from:" + emMessage.getFrom() + "---to:" + emMessage.getTo() + "---nicheng:" + emMessage.getStringAttribute("from_nicheng"));
            } catch (Exception e) {
                cf.refresh();
                Log.i("123---", s + "---from:" + emMessage.getFrom() + "---to:" + emMessage.getTo());
            }
                cf.refresh();
        }
        //透传消息的
        @Override
        public void onCmdMessageReceived(List<EMMessage> list) {
            EMMessage emMessage = list.get(0);
            try{
                EMCmdMessageBody body = (EMCmdMessageBody) emMessage.getBody();
                String action = body.action();
                if (action.equals("isDisable")){//启用和禁止 退出
                   //直接退出app和环信。
                    exitLogin();
                }else if (action.equals("changePassword")){//修改密码  退出
                    exitLogin();
                }else if (action.equals("setRights")){//权限   
                    EventBus.getDefault().post("修改权限");
                    //接收到修改权限的消息。立马去重新获取权限信息
                    reGetRight();
                }else if (action.equals("reloadNickname")){//修改用户资料  刷新个人中心和首页
                    EventBus.getDefault().post("修改资料");
                    //刷新本页面
                    requestInfo();
                }
               
            }catch (Exception e){
                
            }
            
        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }

        @Override
        public void onMessageChanged(EMMessage emMessage, Object o) {

        }
    };

给消息列表添加点击监听:

3.给消息列表设置点击事件,点击跳到聊天界面。(先从好友列表聊天才会产生消息列表)
cf.setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {
            @Override
            public void onListItemClicked(EMConversation conversation) {
                // 聊天需要的bundle对象
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(EaseConstant.EXTRA_USER_ID, conversation.getLastMessage().getUserName());
                bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                intent.putExtras(bundle);
                /**
                 * 从会话列表跳转到聊天页面
                 * 首先要判断最后一条信息是接收还是发送消息
                 * 然后分情况传递头像和昵称
                 *
                 */
                EMMessage lastMessage = conversation.getLastMessage();
                if (lastMessage.direct() == EMMessage.Direct.RECEIVE) {
                    try {
                        intent.putExtra(Utils.FROM_AVATER, lastMessage.getStringAttribute(Utils.FROM_AVATER));
                        intent.putExtra(Utils.FROM_NICHENG, lastMessage.getStringAttribute(Utils.FROM_NICHENG));
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        intent.putExtra(Utils.FROM_AVATER, lastMessage.getStringAttribute(Utils.TO_AVATER));
                        intent.putExtra(Utils.FROM_NICHENG, lastMessage.getStringAttribute(Utils.TO_NICHENG));
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
                startActivity(intent);
            }
        });


activity销毁的时候记得移除消息的监听:

EMClient.getInstance().chatManager().removeMessageListener(emMessageListener);  

四、结束语

大致集成步骤就是这样的,集成环信之前如果对环信一点都不了解建议先去环信上看一下文档。文章纯属按照自己的项目开发需求写的。大家可做参考。


 
















2014-01-21 15:11:00 weixin_33919941 阅读数 25

  

这份代码写出来有些时候了,一直没共享,现在把它共享给大家。简单列一下代码中你可以学到的知识点:

  1. 自定义控件的实现方式;
  2. 事件的拦截分发消费机制;
  3. QQ会话列表滑动删除原理;

最后附上源码链接:QQ消息列表滑动删除.rar (注:转载请注明出处 http://www.cnblogs.com/sunzn/ )

Android 列表

阅读数 389

没有更多推荐了,返回首页