前言:
因为最近要做一个类似IM的聊天界面的效果 当然网上一大把我就不啰嗦了直接上代码。
效果图
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d8e0e8"
android:orientation="vertical">
<ListView
android:id="@+id/msg_list_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="#0000">
</ListView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="@+id/send_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="image"/>
<Button
android:id="@+id/send"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"/>
<EditText
android:id="@+id/input_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@id/send_image"
android:layout_toLeftOf="@id/send"
android:hint="Typ something in here"
android:maxLines="2"
/>
</RelativeLayout>
</LinearLayout>
布局就一个简单的listview 装载我们的消息信息 底部是输入框和2个button分别发送文字和图片的
具体逻辑
adapter = new MsgAdapter(MainActivity.this, R.layout.item, msgList);
inputText = (EditText) findViewById(R.id.input_text);
send = (Button) findViewById(R.id.send);
sendImage=findViewById(R.id.send_image);
dataList=SharedPreferenceUtil.getSelectBean(mContext,"msg");
if(dataList!=null&&dataList.size()>0){
msgList.addAll(dataList);
}
msgListView = (ListView) findViewById(R.id.msg_list_view);
msgListView.setAdapter(adapter);
发送文本消息
send.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
String content = inputText.getText().toString();
if(!"".equals(content)){
if(!flag){
Msg msg = new Msg(content, Msg.SENT,"");
msgList.add(msg);
flag=true;
}else{
Msg msg = new Msg(content, Msg.RECEIVED,"");
msgList.add(msg);
flag=false;
}
if(msgList!=null&&msgList.size()>0){
SharedPreferenceUtil.putSelectBean(mContext,msgList,"msg");
}
adapter.notifyDataSetChanged();//有新消息时,刷新ListView中的显示
msgListView.setSelection(msgList.size());//将ListView定位到最后一行
inputText.setText("");//清空输入框的内容
}
}
});
这边为了模拟发送和接收消息我们写了一个布尔值来循环添加消息到msgList 集合中
发送图片
sendImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openPhoto(2);
}
});
/**
* 从相册中选择图片
*/
private void openPhoto(int openPhotoCode){
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, openPhotoCode);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == 2) {
// 从相册返回的数据
if (data != null) {
// 得到图片的全路径
Uri uri = data.getData();
String imagePath=ImageUtils.getImagePath(uri, null, (Activity) mContext);
if(!imgflag){
Msg msg = new Msg("", Msg.SENT,imagePath);
msgList.add(msg);
imgflag=true;
}else{
Msg msg = new Msg("", Msg.RECEIVED,imagePath);
msgList.add(msg);
imgflag=false;
}
if(msgList!=null&&msgList.size()>0){
SharedPreferenceUtil.putSelectBean(mContext,msgList,"msg");
}
adapter.notifyDataSetChanged();//有新消息时,刷新ListView中的显示
msgListView.setSelection(msgList.size());//将ListView定位到最后一行
// inputText.setText("");//清空输入框的内容
}
}
}
我们在 onActivityResult回调方法中拿到图片的uri 然后转成path字符串添加到msgList 中
uri 转path工具类
package com.example.imtest;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
public class ImageUtils {
public static String getImagePath(Uri uri, String selection, Activity activity) {
String path = null;
Cursor cursor = activity.getContentResolver().query(uri,
null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
}
消息Bean类
package com.example.imtest;
public class Msg{
public static final int RECEIVED = 0;//收到一条消息
public static final int SENT = 1;//发出一条消息
private String content;//消息的内容
private int type;//消息的类型
private String imgUrl;
public Msg(String content, int type, String imgUrl) {
this.content = content;
this.type = type;
this.imgUrl = imgUrl;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
我们分别定义了2个常量和3个变量分辨来装载消息内容 消息类型和图片路径url
消息列表适配器
public class MsgAdapter extends ArrayAdapter<Msg>{
private int resourceId;
public MsgAdapter(Context context, int textViewresourceId, List<Msg> objects) {
super(context, textViewresourceId, objects);
resourceId = textViewresourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Msg msg = getItem(position);
View view;
ViewHolder viewHolder;
if(convertView == null){
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.leftLayout = (LinearLayout)view.findViewById(R.id.left_layout);
viewHolder.rightLayout = (LinearLayout)view.findViewById(R.id.right_Layout);
viewHolder.leftMsg = (TextView)view.findViewById(R.id.left_msg);
viewHolder.rightMsg = (TextView)view.findViewById(R.id.right_msg);
viewHolder.leftImage=view.findViewById(R.id.left_image);
viewHolder.rightImage=view.findViewById(R.id.right_image);
viewHolder.leftMsglayout=view.findViewById(R.id.left_msg_layout);
viewHolder.rightMsglayout=view.findViewById(R.id.right_msg_layout);
view.setTag(viewHolder);
}else{
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
if(msg.getType()==Msg.RECEIVED){
//如果是收到的消息,则显示左边消息布局,将右边消息布局隐藏
viewHolder.leftLayout.setVisibility(View.VISIBLE);
viewHolder.rightLayout.setVisibility(View.GONE);
if(!TextUtils.isEmpty(msg.getImgUrl())){
viewHolder.leftMsglayout.setVisibility(View.GONE);
viewHolder.leftImage.setVisibility(View.VISIBLE);
File file = new File(msg.getImgUrl());
Glide.with(mContext).load(file).into(viewHolder.leftImage);
}else{
viewHolder.leftImage.setVisibility(View.GONE);
viewHolder.leftMsglayout.setVisibility(View.VISIBLE);
viewHolder.leftMsg.setText(msg.getContent());
}
}else if(msg.getType()==Msg.SENT){
//如果是发出去的消息,显示右边布局的消息布局,将左边的消息布局隐藏
viewHolder.rightLayout.setVisibility(View.VISIBLE);
viewHolder.leftLayout.setVisibility(View.GONE);
viewHolder.rightMsg.setText(msg.getContent());
if(!TextUtils.isEmpty(msg.getImgUrl())){
viewHolder.rightMsglayout.setVisibility(View.GONE);
viewHolder.rightImage.setVisibility(View.VISIBLE);
File file = new File(msg.getImgUrl());
Glide.with(mContext).load(file).into(viewHolder.rightImage);
}else{
viewHolder.rightImage.setVisibility(View.GONE);
viewHolder.rightMsglayout.setVisibility(View.VISIBLE);
viewHolder.rightMsg.setText(msg.getContent());
}
}
return view;
}
class ViewHolder{
LinearLayout leftLayout;
LinearLayout rightLayout;
TextView leftMsg;
TextView rightMsg;
ImageView leftImage;
ImageView rightImage;
LinearLayout leftMsglayout;
LinearLayout rightMsglayout;
}
}
适配器中我们跟进消息类型来判断是事显示左边布局还是显示右边布局 我们通过对 getImgUrl 的空判来处理是显示图片还是文本消息即可实现需求。到此Android 实现IM聊天 布局效果就讲完了
最后总结:
这种效果网上有很多帖子 毕竟安卓也发展了10多年了肯定又很多大神 写过也发过了我这边也只是 有这种需求 而且不能用三方库实现 我就自己撸一下 其实有其他方式实现的 lsitview多布局 或者recylerview 多布局都可以实现我这边就不展开细说 有兴趣·的朋友可以自己去尝试下。 最后希望我的每一篇文章都能网友和社区提供到帮助 ,以后我还会贡献更多有用的代码分享给大家。各位同学如果觉得文章还不错 ,麻烦给关注和star,小弟在这里谢过啦