当前位置: 首页 > news >正文

安卓实现左右布局聊天界面

先看效果图。是不是你们想要的。大概就是这样的效果

Android 实现左右布局聊天界面(好友左、自己右)
采用 RecyclerView + 双布局 Item 实现,结构清晰、可直接复用,适配聊天气泡样式。
一、整体思路
两种 Item 布局:
item_msg_left.xml:对方消息(居左)
item_msg_right.xml:自己消息(居右)
消息实体类:记录消息内容、发送者类型
RecyclerView 适配器:根据类型加载不同布局
气泡背景:自带圆角、区分左右样式
二、1. 消息实体类 MsgBean

publicclassMsgBean{// 消息文本privateStringcontent;// 0=对方消息(左) 1=自己消息(右)privateintmsgType;publicMsgBean(Stringcontent,intmsgType){this.content=content;this.msgType=msgType;}// getter & setterpublicStringgetContent(){returncontent;}publicintgetMsgType(){returnmsgType;}}

三、2. 左边 Item 布局(对方消息)item_msg_left.xml

<?xml version="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:padding="10dp"android:gravity="left"><TextViewandroid:id="@+id/tv_msg"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="10dp"android:maxWidth="250dp"android:textColor="#333333"android:background="@drawable/bg_msg_left"/></LinearLayout>
  1. 右边 Item 布局(自己消息)item_msg_right.xml
<?xml version="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:padding="10dp"android:gravity="right"><TextViewandroid:id="@+id/tv_msg"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="10dp"android:maxWidth="250dp"android:textColor="#FFFFFF"android:background="@drawable/bg_msg_right"/></LinearLayout>

四、4. 气泡背景 drawable
bg_msg_left.xml(左侧灰色气泡)

<?xml version="1.0"encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#E5E5E5"/><corners android:topLeftRadius="5dp"android:topRightRadius="15dp"android:bottomLeftRadius="15dp"android:bottomRightRadius="15dp"/></shape>

bg_msg_right.xml(右侧蓝色气泡)

<?xml version="1.0"encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#0099FF"/><corners android:topLeftRadius="15dp"android:topRightRadius="5dp"android:bottomLeftRadius="15dp"android:bottomRightRadius="15dp"/></shape>

五、5. RecyclerView 适配器 MsgAdapter

importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.TextView;importandroidx.annotation.NonNull;importandroidx.recyclerview.widget.RecyclerView;importjava.util.List;publicclassMsgAdapterextendsRecyclerView.Adapter<RecyclerView.ViewHolder>{privatefinalList<MsgBean>msgList;// 区分两种布局类型privatestaticfinalintTYPE_LEFT=0;privatestaticfinalintTYPE_RIGHT=1;publicMsgAdapter(List<MsgBean>msgList){this.msgList=msgList;}// 根据消息类型返回布局@OverridepublicintgetItemViewType(intposition){returnmsgList.get(position).getMsgType();}@NonNull@OverridepublicRecyclerView.ViewHolderonCreateViewHolder(@NonNullViewGroupparent,intviewType){if(viewType==TYPE_LEFT){Viewview=LayoutInflater.from(parent.getContext()).inflate(R.layout.item_msg_left,parent,false);returnnewLeftHolder(view);}else{Viewview=LayoutInflater.from(parent.getContext()).inflate(R.layout.item_msg_right,parent,false);returnnewRightHolder(view);}}@OverridepublicvoidonBindViewHolder(@NonNullRecyclerView.ViewHolderholder,intposition){MsgBeanbean=msgList.get(position);if(holderinstanceofLeftHolder){((LeftHolder)holder).tvMsg.setText(bean.getContent());}elseif(holderinstanceofRightHolder){((RightHolder)holder).tvMsg.setText(bean.getContent());}}@OverridepublicintgetItemCount(){returnmsgList.size();}// 左边ViewHolderstaticclassLeftHolderextendsRecyclerView.ViewHolder{TextViewtvMsg;publicLeftHolder(@NonNullViewitemView){super(itemView);tvMsg=itemView.findViewById(R.id.tv_msg);}}// 右边ViewHolderstaticclassRightHolderextendsRecyclerView.ViewHolder{TextViewtvMsg;publicRightHolder(@NonNullViewitemView){super(itemView);tvMsg=itemView.findViewById(R.id.tv_msg);}}// 添加消息 + 自动滚动到底部publicvoidaddMsg(MsgBeanbean){msgList.add(bean);notifyItemInserted(msgList.size()-1);}}

六、6. 主界面布局 activity_chat.xml

<?xml version="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><!--聊天列表--><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recycler_chat"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"/><!--输入栏--><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:padding="8dp"><EditTextandroid:id="@+id/et_input"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:hint="输入消息"/><Buttonandroid:id="@+id/btn_send"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送"/></LinearLayout></LinearLayout>

七、7. 聊天 Activity 逻辑 ChatActivity.java

importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroidx.appcompat.app.AppCompatActivity;importandroidx.recyclerview.widget.LinearLayoutManager;importandroidx.recyclerview.widget.RecyclerView;importjava.util.ArrayList;importjava.util.List;publicclassChatActivityextendsAppCompatActivity{privateRecyclerViewrecyclerChat;privateEditTextetInput;privateMsgAdaptermsgAdapter;privateList<MsgBean>msgList;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_chat);recyclerChat=findViewById(R.id.recycler_chat);etInput=findViewById(R.id.et_input);ButtonbtnSend=findViewById(R.id.btn_send);// 初始化列表msgList=newArrayList<>();msgAdapter=newMsgAdapter(msgList);LinearLayoutManagerlayoutManager=newLinearLayoutManager(this);recyclerChat.setLayoutManager(layoutManager);recyclerChat.setAdapter(msgAdapter);// 模拟对方默认消息msgAdapter.addMsg(newMsgBean("你好呀",0));// 发送按钮点击btnSend.setOnClickListener(v->{Stringcontent=etInput.getText().toString().trim();if(!content.isEmpty()){// 添加自己消息(右)msgAdapter.addMsg(newMsgBean(content,1));etInput.setText("");// 自动滚动到底部recyclerChat.scrollToPosition(msgAdapter.getItemCount()-1);}});}}

效果说明
1.好友消息:左侧灰色气泡
2.自己消息:右侧蓝色气泡
3.发送消息自动滚到底部
4.消息最大宽度限制,长文本自动换行
八、软键盘弹出自动上移聊天列表(安卓聊天界面必备)
默认情况下:弹出输入法键盘时,RecyclerView 聊天列表不会往上顶,输入框会被键盘遮挡、最新消息被键盘盖住看不到。
软键盘弹起 → 整个聊天布局自动上移
最新消息自动显示在键盘上方,不会被遮挡

AndroidManifest.xml 配置(最简单,一行搞定)
找到你的 ChatActivity 对应的 activity 标签,添加属性:

android:windowSoftInputMode="adjustResize"

完整示例:

<activityandroid:name=".ChatActivity"android:windowSoftInputMode="adjustResize"></activity>
http://www.jsqmd.com/news/745801/

相关文章:

  • 告别繁琐的jdk安装与配置,用快马平台ai助手极速生成java项目代码
  • AI智能体如何通过drawio-skill实现自然语言生成工程图表
  • 实战应用:通过快马快速构建vmware虚拟机网络安全攻防靶场
  • S32K144 UDS Bootloader实战:从NXP官方例程到ECUBus上位机刷写的完整避坑记录
  • 音乐数字枷锁的解放者:浏览器端音频解密技术深度解析
  • 如何在Mac上实现百度网盘极速下载?BaiduNetdiskPlugin-macOS插件深度解析
  • 手把手教你离线搞定Ubuntu 18.04的GLIBC升级:从报错到成功运行新软件
  • 实战演练:基于快马生成代码开发九么动漫社区网站首页
  • 16.人工智能实战:大模型回答格式总是不稳定?JSON Schema 约束、重试修复与结构化输出完整方案
  • 【等保四级医疗系统改造实战白皮书】:20年资深架构师亲授Java系统合规落地的7大生死关卡
  • AI赋能开发:在快马平台直接调用AI模型,智能生成天气预报小程序完整代码
  • 终极指南:如何在Windows上免模拟器安装APK文件?APK Installer完整教程
  • 保姆级教程:用Hugging Face上的VITS-Uma模型,5分钟搞定原神/崩铁角色语音合成
  • OpenClaw技术架构与智能体
  • 前端新手福音:用快马平台和ccswitch轻松理解状态管理
  • 人工智能篇---TensorBoard 和 Weights Biases (WB)
  • 从Blender到Unity:一个低多边形古宅模型的完整美术管线实战(含材质球提取与后期调整)
  • 免费获取金融数据的终极指南:Yahoo Finance API完整教程
  • 自托管AI编码代理编排平台sandboxed.sh部署与配置指南
  • Qt处理CSV文件时,你踩过QTextStream和QByteArray的坑吗?
  • 仅限前200名:Python标注配置黄金配置集(含mypy插件定制+vscode智能提示增强+CI拦截规则),GitHub Star 4.2k项目内部流出
  • 初创团队如何通过 Taotoken 统一管理多个 AI 模型的开发与成本
  • 借助用量看板分析API调用模式并优化模型选型策略
  • 从官方Demo到实战:手把手教你用Odin的ValidateInput和ValueDropdown打造防呆编辑器
  • 5个实战技巧:彻底解决Mesa3D Windows驱动部署难题
  • 17.人工智能实战:Agent 工具调用总是乱选?从意图识别到 Tool Router 的可靠调用架构设计
  • 告别Host模式!PowerJob-Server在Docker桥接网络下的正确配置姿势(附完整Compose文件)
  • World Action Model的本质:视频动作统一建模
  • 当网盘下载不再烦恼:LinkSwift如何让文件获取变得简单
  • 鸿蒙系统开发者如何快速接入大模型服务,使用Taotoken实现多模型调用