从0系统学Android--3.7 聊天界面编写

1,715 阅读4分钟

从0系统学Android--3.7 聊天界面编写

本系列文章目录更多精品文章分类

本系列持续更新中....

3.7 编写界面的最佳实践

前面学习了那么多 UI 开发的知识,下面来进行实践,做一个美观的聊天界面。

3.7.1 制作 Nine-Patch 图片

实战前先学习一个小知识,如何制作 Nine-Patch 图片。

Nine-Patch 是一种被特殊处理的 .png图片,能够指定那些区域可以被拉伸,那些区域不可以。

来看看 Nine-Patch 图片的实际作用。

首先我们用一张普通的图片作为背景

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

运行结果

可以看到效果非常糟糕,由于图片的宽度不能填满整个屏幕的宽度,整张图片就被均匀的拉伸的,效果很差,这种情况,我们就可以使用 Nine-Patch 图片来进行改善了。

如何创建 nine-patch 图片呢?

首先在 Android Studio 中选中你要变成 nine-patch 的图片,然后右击--->Create 9-Patch file 就可以创建 Nine-Patch 图片了。

我们可以在图片的四个边框绘制一个个的小黑点。在上边框和左边框的部分表示当前图片需要拉伸的时候就会拉伸黑色点标记的区域,在下边框和右边框的部分表示内容会被放置的区域。用鼠标在图片的边缘拖到就可以进行绘制了。按住 Shift 键拖动可以进行擦除。

再来看看使用 nine-patch 的效果

这样当图片需要拉伸的时候就只拉伸指定区域了。

3.7.2 编写精美的聊天界面

聊天界面肯定有收到的消息和发送的消息,上面我们已经把发送消息的背景图制作好了,再制作一张发送消息的背景图。

图片资源都准备好了,就可以写代码了。

编写主页面布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rlv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/et_info"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="发送信息"
            android:maxLines="2"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发送"
            android:id="@+id/bt_send"/>
    </LinearLayout>
</LinearLayout>

建立聊天的消息对象

public class Msg {
    public static final  int TYPE_RECEIVE = 0;
    public static final int TYPE_SEND = 1;
    private String content;

    public Msg(String content, int type) {
        this.content = content;
        this.type = type;
    }

    private int type;

    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;
    }
}

type 用来指定消息的类型,是发送的消息还接受的消息

然后编写 RecyclerView 的子项布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:orientation="vertical">
    <LinearLayout
        android:id="@+id/ll_left"
        android:background="@mipmap/message_left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/tv_left"
            android:textColor="#FFF"
            android:layout_margin="10dp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_gravity="right"
        android:id="@+id/ll_right"
        android:background="@mipmap/message_right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/tv_right"
            android:layout_margin="10dp"/>

    </LinearLayout>
</LinearLayout>

这里我们把接受消息和发送消息的布局都写进来了,代码中根据消息的类型来调用 visible 方法,显示对应的消息。

建立适配器

public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.MsgViewHolder> {
    private List<Msg> list;
    public MsgAdapter(List<Msg> list){
        this.list = list;
    }



    class MsgViewHolder extends RecyclerView.ViewHolder{
        LinearLayout llLeft,llRight;
        TextView tvLeft,tvRight;

        public MsgViewHolder(@NonNull View itemView) {
            super(itemView);
            llLeft =itemView.findViewById(R.id.ll_left);
            llRight =itemView.findViewById(R.id.ll_right);
            tvLeft =itemView.findViewById(R.id.tv_left);
            tvRight =itemView.findViewById(R.id.tv_right);
        }
    }

    @NonNull
    @Override
    public MsgViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
        MsgViewHolder viewHolder = new MsgViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MsgViewHolder holder, int position) {
        Msg msg = list.get(position);
        // 这里根据消息的类型来选择不同的布局
        if (msg.getType() == Msg.TYPE_RECEIVE){
            holder.llLeft.setVisibility(View.VISIBLE);
            holder.llRight.setVisibility(View.GONE);
            holder.tvLeft.setText(msg.getContent());
        }else {
            holder.llRight.setVisibility(View.VISIBLE);
            holder.llLeft.setVisibility(View.GONE);
            holder.tvRight.setText(msg.getContent());
        }

    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}

然后写 Activity 代码

public class MsgActivity extends AppCompatActivity {

    List<Msg> list  =new ArrayList<>();
    EditText text ;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nine_patch);
        initData();
        final RecyclerView recyclerView  = findViewById(R.id.rlv);
        final MsgAdapter msgAdapter = new MsgAdapter(list);
         text = findViewById(R.id.et_info);
        Button bt = findViewById(R.id.bt_send);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(msgAdapter);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Random random = new Random();
                // 这里还是利用随机数来生成消息的类型
                int count = random.nextInt(20);
                Msg msg = new Msg(text.getText()+"count:"+count,count%2);
                list.add(msg);
                // 表示在消息的末尾插入内容
                msgAdapter.notifyItemInserted(list.size()-1);
                // 让 RecyclerView 自动滚动到最底部
                recyclerView.scrollToPosition(list.size()-1);
                // 清空内容
                text.setText("");
            }
        });
    }

    public void initData(){
        Random random = new Random();
        for (int i=0;i<40;i++){
            int count = random.nextInt(20);
            Msg msg = new Msg("消息嗯哼"+i+"count:"+count,count%2);
            list.add(msg);
        }


    }
}

notifyItemInserted() 方法,用于通知列表有新的数据插入了,这样新增加的一条消息才能显示出来。

scrolltoPosition() 方法将数据定位到最后一行,保证我们可以看到最后发送的内容。