Android之编写聊天界面实践

(前提)制作Nine-Path图片
在我的上一节有详细讲解。
制作Nine-Path图片
效果图

编写精美的聊天界面:

既然是要编写一个聊天界面,那肯定要收到的消息和发出的消息。
我们刚刚制作的pop.9.png可以作为收到消息的背景图,那么毫无疑问你还需要再制作一张pop_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中的代码,如下所示:

<?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: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用于显示聊天记录的内容,有放置了一个EditText用于输入消息,还放置了一个Button用于发送消息。
然后定义消息的实体类,新建Msg,代码如下所示:

package net.nyist.lenovo.message_agetest;
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代码如下:

<?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="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:background="@drawable/pop">
    <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作为背景图。
接下来需要创建RecycerView的适配器类,新建类MsgAdapter,代码如下:

package net.nyist.lenovo.message_agetest;
	
	import android.support.v7.widget.RecyclerView;
	import android.view.LayoutInflater;
	import android.view.View;
	import android.view.ViewGroup;
	import android.widget.LinearLayout;
	import android.widget.TextView;
	
	import java.util.List;
	
	
	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();
    }
	}

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

package net.nyist.lenovo.message_agetest;
	
	import android.support.v7.app.AppCompatActivity;
	import android.os.Bundle;
	import android.support.v7.widget.LinearLayoutManager;
	import android.support.v7.widget.RecyclerView;
	import android.view.View;
	import android.widget.Button;
	import android.widget.EditText;
	import android.widget.LinearLayout;
	
	import java.util.ArrayList;
	import java.util.List;
	
	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);//当有消息时,刷新ListView中的显示
                    msgRecyclerView.scrollToPosition(msgList.size() - 1);//将ListView定位到最后一行
                    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 Tom.Nice to meet you.",Msg.TYPE_RECEIVED );
        msgList.add(msg3);
    }
	}

在initMsgs()方法中我们先初始化了几条数据用于在RecyclerView中显示。然后再发送按钮的点击事件里获取了EditText中的内容,如果内容不为null则创建出一个新的Msg对象,并把它添加到msgList列表中去。之后又调用了适配器的notifyItemInserted()方法,用于通知列表有新的数据插入,这样新增的一条消息才能够在RecyclerView中显示。接着调用RecyclerView的scrollToPosition()方法将显示的数据定位到最后一行,以保证一定可以看得到最后发出的一条消息。最后调用EditText的setText的setText()方法将输入的内容清空。

猜你喜欢

转载自blog.csdn.net/i_nclude/article/details/75449110