《第一行代码》学习之编写聊天界面

编写聊天界面,就会有收到消息和发出消息。
制作出message_left.9.png和message_right.9.png分别作为发送和接收消息的背景图。

程序会用到RecyclerView,因此首先需要在app/build.gradle当中添加依赖库,如下所示:

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

接下来编写主界面,修改activity_main.xml中的代码,如下所示:

<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">

        <!--android:hint="Type something here"是输入框的提示词-->
        <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" />

        <!--android:textAllCaps="false"禁止系统对Send中所有英文字母自动进行大小写转换,Button宽度仍按照wrap_content算,而
        EditTest会占满屏幕所有剩余空间-->
        <Button
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send"
            android:textAllCaps="false"/>
    </LinearLayout>

</LinearLayout>

在主界面放置了一个RecyclerView用于显示聊天内容,放置一个EditText用于输入消息,防止一个Button用于发送消息。

然后定义消息的实体类,新建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_RECEIVED表示一条收到的消息,TYPE_SENT表示一条发出的消息。

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

<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="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="left"
                  android:background="@drawable/message_left" >

                  <TextView
                      android:id="@+id/left_msg"
                      android:layout_width="wrap_content"
                      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="wrap_content"
                  android:layout_gravity="right"
                  android:background="@drawable/message_right">

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

这里让收到的消息居左对齐,发出的消息居右对齐,并且分别使用message_left.9.png和message_right.9.png作为背景图。运用可见属性,稍后在代码中根据消息的类型来决定隐藏和显示哪种信息,就可以让收到的消息和发出的消息都放在同一个布局里。

接下来需要创建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) {
        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) {
        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();
    }
}

在onBindViewHolder()方法中增加了对消息类型的判断。如果消息是收到的,则显示左边的消息布局,如果消息是放出的,则显示右边的消息布局。

最后修改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);
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if(!"".equals(content)) {
                    Msg msg = new Msg(content, Msg.TYPE_SENT);
                    msgList.add(msg);
                    adapter.notifyItemInserted(msgList.size() - 1);  //当有新消息时,刷新RecyclerView中的显示
                    msgRecyclerView.scrollToPosition(msgList.size() - 1); //将RecyclerView定位到最后一行
                    inputText.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 zhuzx. Nice talking to you.", Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
}

在initMsgs()方法中初始化了几条数据用于在RecyclerView中显示。在发送按钮的点击事件里获取EditText中的内容,如果内容不为空字符串则创建出一个新的Msg对象,并把它添加到msgList列表中去。调用适配器noyifyItemInserted()方法,用于通知列表有新的数据插入,这样新增的一条消息才能够在RecyclerView中显示。调用RecyclerView的scrollToPosition()方法将显示的数据定位到最后一行,以保证一定可以看到最后一条消息。最后调用EditText的setText()方法将输入的内容清空。
成果如下:
这里写图片描述 这里写图片描述
可惜有个问题,当有多条对话时,点击输入框,并不能显示出最后一条消息,这个网上查了下,我水平low,没有解决好,以后再回来解决吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值