温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Android中利用RecyclerView实现一个聊天界面

发布时间:2021-01-20 16:42:50 来源:亿速云 阅读:372 作者:Leah 栏目:移动开发

这篇文章给大家介绍如何在Android中利用RecyclerView实现一个聊天界面,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

具体内容如下

1、首先在app/build.gradle(注意有两个build.gradle,选择app下的那个)当中添加依赖库,如下:

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 compile 'com.android.support:appcompat-v7:24.2.1'
 compile 'com.android.support:recyclerview-v7:24.2.1'
 testCompile 'junit:junit:4.12'
 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  exclude group: 'com.android.support', module: 'support-annotations'
 })
}

添加完之后记得点击Sync Now进行同步。

2、开始编写主界面,修改activity_main.xml中的代码,如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/activity_main"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#d8e0e8"
 >
 <android.support.v7.widget.RecyclerView
  android:id="@+id/msg_recycler_view"
  android:layout_width="match_parent"
  android:layout_height="0dp"
  android:layout_weight="1"
  />
 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content">
  <EditText
   android:id="@+id/input_text"
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_weight="1"
   android:hint="Type something here"
   android:maxLines="2"
   />
  <Button
   android:id="@+id/send"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="send"
   />
 </LinearLayout>
</LinearLayout>

RecyclerView用于显示聊天的消息内容(因为不是内置在系统SDK中的,所以需要把完整的包路径写出来);

放置一个EditView用于输入消息,一个Button用于发送消息。

3、定义消息的实体类,新建Msg,代码如下:

public class Msg {
 public static final int TYPE_RECEIVED=0;
 public static final int TYPE_SENT=1;
 private String content;
 private int type;
 public Msg(String content,int type){
  this.content=content;
  this.type=type;
 }
 public String getContent(){
  return content;
 }

 public int getType(){
  return type;
 }
}

Msg只有两个字段,content表示消息的内容,type表示消息的类型(二值可选,一个是TYPE_RECRIVED,一个是TYPE_SENT)。

4、接着编写RecyclerView子项的布局,新建msg_item.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:padding="10dp"
 >

 <LinearLayout
  android:id="@+id/left_layout"
  android:layout_width="283dp"
  android:layout_height="106dp"
  android:layout_gravity="left"
  android:background="@drawable/zuo"
  android:weightSum="1">

  <TextView
   android:id="@+id/left_msg"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_gravity="center"
   android:layout_margin="10dp"
   />
 </LinearLayout>

 <LinearLayout
  android:id="@+id/right_layout"
  android:layout_width="229dp"
  android:layout_height="109dp"
  android:layout_gravity="right"
  android:background="@drawable/you"
  >
  <TextView
   android:id="@+id/right_msg"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center"
   android:layout_margin="10dp"
   />
 </LinearLayout>

</LinearLayout>

收到的消息局左对齐,发出的消息居右对齐,并用相应的图片作为背景。

5、创建RecyclerView的适配器类,新建MsgAdapter,代码如下:

public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
 private List<Msg> mMsgList;
 static class ViewHolder extends RecyclerView.ViewHolder{
  LinearLayout leftLayout;
  LinearLayout rightLayout;
  TextView leftMsg;
  TextView rightMsg;
  public ViewHolder(View view){
   super(view);
   leftLayout=(LinearLayout)view.findViewById(R.id.left_layout);
   rightLayout=(LinearLayout)view.findViewById(R.id.right_layout);
   leftMsg=(TextView)view.findViewById(R.id.left_msg);
   rightMsg=(TextView)view.findViewById(R.id.right_msg);
  }
 }
 public MsgAdapter(List<Msg> msgList){
  mMsgList=msgList;
 }
 @Override
 public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){    
 //onCreateViewHolder()用于创建ViewHolder实例
  View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
  return new ViewHolder(view);             
 //把加载出来的布局传到构造函数中,再返回
 }
 @Override
 public void onBindViewHolder(ViewHolder Holder,int position){      
 //onBindViewHolder()用于对RecyclerView子项的数据进行赋值,会在每个子项被滚动到屏幕内的时候执行
  Msg msg=mMsgList.get(position);
  if(msg.getType()==Msg.TYPE_RECEIVED){           
 //增加对消息类的判断,如果这条消息是收到的,显示左边布局,是发出的,显示右边布局
   Holder.leftLayout.setVisibility(View.VISIBLE);
   Holder.rightLayout.setVisibility(View.GONE);
   Holder.leftMsg.setText(msg.getContent());
  }else if(msg.getType()==Msg.TYPE_SENT) {
   Holder.rightLayout.setVisibility(View.VISIBLE);
   Holder.leftLayout.setVisibility(View.GONE);
   Holder.rightMsg.setText(msg.getContent());
  }
 }
 @Override
 public int getItemCount(){
  return mMsgList.size();
 }
}

6、最后修改MainActivity中的代码,来为RecyclerView初始化一些数据,并给发送按钮加入事件响应,代码如下:

public class MainActivity extends AppCompatActivity {
 private List<Msg> msgList=new ArrayList<>();
 private EditText inputText;
 private Button send;
 private RecyclerView msgRecyclerView;
 private MsgAdapter adapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initMsgs();               //初始化消息数据
  inputText=(EditText)findViewById(R.id.input_text);
  send=(Button)findViewById(R.id.send);
  msgRecyclerView=(RecyclerView)findViewById(R.id.msg_recycler_view);

  LinearLayoutManager layoutManager=new LinearLayoutManager(this); 

  //LinearLayoutLayout即线性布局,创建对象后把它设置到RecyclerView当中
  msgRecyclerView.setLayoutManager(layoutManager);

  adapter=new MsgAdapter(msgList);         

  //创建MsgAdapter的实例并将数据传入到MsgAdapter的构造函数中
  msgRecyclerView.setAdapter(adapter);

  send.setOnClickListener(new View.OnClickListener(){     

 //发送按钮点击事件
   @Override
   public void onClick(View v){
    String content=inputText.getText().toString();    

  //获取EditText中的内容
    if(!"".equals(content)){         

  //内容不为空则创建一个新的Msg对象,并把它添加到msgList列表中
     Msg msg=new Msg(content,Msg.TYPE_SENT);
     msgList.add(msg);
     adapter.notifyItemInserted(msgList.size()-1);   

  //调用适配器的notifyItemInserted()用于通知列表有新的数据插入,这样新增的一条消息才能在RecyclerView中显示
     msgRecyclerView.scrollToPosition(msgList.size()-1); 

  //调用scrollToPosition()方法将显示的数据定位到最后一行,以保证可以看到最后发出的一条消息
     inputText.setText("");         

  //调用EditText的setText()方法将输入的内容清空
    }
   }
  });
 }

 private void initMsgs(){
  Msg msg1=new Msg("Hello guy.",Msg.TYPE_RECEIVED);
  msgList.add(msg1);
  Msg msg2=new Msg("Hello.Who is that?",Msg.TYPE_SENT);
  msgList.add(msg2);
  Msg msg3=new Msg("This is Tom!",Msg.TYPE_RECEIVED);
  msgList.add(msg3);
 }
}

关于如何在Android中利用RecyclerView实现一个聊天界面就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI