学习目的:1.编写简单聊天软件
思路:1.主界面:输入框 发送按钮 2.新建Msg类 3.编写RecyclerView的子布局 4.可见属性(使发送 接受的消息在同一布局内)
5.创建RecycleView的适配类
1.主界面(简单 ,不赘述)
1 | <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" |
2.新建Msg类
1 | ublic class Msg { |
3.编写RecyclerView的子布局
1 | <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" |
5.创建RecycleView的适配类MsgAdaper
1 | public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> { |
6.MainActivity类
private List<Msg> msgList = new ArrayList<Msg>();
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中的显示
//不是RecycleView吗?
msgRecyclerView.scrollToPosition(msgList.size() - 1); // 将ListView定位到最后一行
//不是RecycleView吗?
inputText.setText(""); // 清空输入框中的内容
}
}
});