RecyclerView实现聊天界面

 目前在根据《第一行代码》学习安卓开发,没有恒心断断续续的,所以准备通过写博客来促进自己学习。从第三章RecyclerView开始,会把学习过程中遇到的问题和解决方法都写出来,希望自己能有收获。

1.首先在app/build.grade当中添加依赖库

 

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

添加完后SyncNow同步一下,需要注意recyclerview后面跟的版本号需要和appcompat的版本号一致才可以,否则同步会报错。PS:从网上找了好久,最后尝试了一下没想到好了。

2.制作气泡图片,百度一下找了两个气泡图片,一左一右。右键图片 create 9-patch file,打开生成的文件,

3.编写主界面,修改activity_main.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="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:maxLines="2"
            android:hint="Type something here"/>
        <Button
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send"/>
    </LinearLayout>
</LinearLayout>

界面如下:



4.编写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;
    }
}

5.接下来写RecyclerView子项的布局,新建msg_item.xml,代码如下

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="10dp">

        <LinearLayout
            android:id="@+id/left_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:background="@drawable/pnaa"
            tools:layout_editor_absoluteX="177dp"
            tools:layout_editor_absoluteY="0dp">

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

        <LinearLayout
            android:id="@+id/right_layout"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:background="@drawable/pnbb">

            <TextView
                android:id="@+id/right_msg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="10dp"
                android:textColor="#fff" />
        </LinearLayout>

    </LinearLayout>


界面如下:

6.编写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)//传入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> list)
    {
        mMsgList=list;
    }
    public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType)
    {
        View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
        return new ViewHolder(view);
    }//创建ViewHolder实例,加载msg_item布局,
    public void onBindViewHolder(ViewHolder holder,int position)
    {
        Msg msg=mMsgList.get(position);//获取当前的Msg实例
        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.leftLayout.setVisibility(View.GONE);
            holder.rightLayout.setVisibility(View.VISIBLE);
            holder.rightMsg.setText(msg.getContent());
        }
    }//对RecyclerView的子项的数据进行赋值,会在每个子项被滚动到屏幕时执行。
    public int getItemCount()
    {
        return mMsgList.size();//告诉RecyclerView一共有多少子项。直接返回数据源长度。
    }
}
7.
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);
        initMsg();
        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);
        //LayoutManager用来指定RecyclerView的布局方式,layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL)设置横向滚动,StaggeredLayoutManager layoutManager=new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL) 可以设置3列的瀑布排列
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter=new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);
        send.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view)
            {
                String content=inputText.getText().toString();
                if(!"".equals(content))
                {
                    Msg msg=new Msg(content,Msg.TYPE_SENT);
                    msgList.add(msg);
                    adapter.notifyItemInserted(msgList.size()-1);
                    msgRecyclerView.scrollToPosition(msgList.size()-1);
                    inputText.setText("");
                }
            }
        });
    }
    public void initMsg()//初始化信息
    {
        Msg msg1=new Msg("hello guy",Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2=new Msg("hello guy",Msg.TYPE_SENT);
        msgList.add(msg2);
        Msg msg3=new Msg("hello guy",Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
}


运行结果如下:



  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值