Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化

Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)

本文通过自己手写的例子来看如何实现聊天输入框以及RecyclerView与输入框之间的相互适应。

开始之前,我们先自定义一个EditTextView

这个自定义的MyEditTextView是有作用的,主要为了后面消息展示的时候去监控软件盘的关闭,方便消息item的位置调整

package cn.xie.imchat.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;

/**
 * 拦截键盘向下的 EditTextView
 *
 * @author xiejinbo
 * @date 2019/9/29 0029 13:44
 */
public class MyEditTextView extends EditText {

    public MyEditTextView(Context context) {
        super(context);
    }

    public MyEditTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyEditTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == 1) {
            super.onKeyPreIme(keyCode, event);
            onKeyBoardHideListener.onKeyHide(keyCode, event);
            return false;
        }
        return super.onKeyPreIme(keyCode, event);
    }

    /**
     * 键盘监听接口
     */
    OnKeyBoardHideListener onKeyBoardHideListener;

    public void setOnKeyBoardHideListener(OnKeyBoardHideListener onKeyBoardHideListener) {
        this.onKeyBoardHideListener = onKeyBoardHideListener;
    }

    public interface OnKeyBoardHideListener {
        void onKeyHide(int keyCode, KeyEvent event);
    }
}

首先,我们来看看整体输入框布局实现的效果

Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第1张图片

再来看看具体的布局实现

下面的代码就是上面截图的具体实现。整个activity_chat.xml的layout布局中,最外层是LinearLayout,包裹着两个 RelativeLayout,分别是顶部标题栏、下面的输入栏(+聊天信息展示),相信大家都能看得懂。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activity.ChatActivity">

    <!--顶部标题-->
    <RelativeLayout
        android:id="@+id/title"
        style="@style/HeadRelativeLayout">

        <ImageView
            android:id="@+id/back"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@mipmap/back"
            android:layout_marginLeft="10dp"/>

        <TextView
            android:id="@+id/chat_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="聊天人称呼"
            android:textColor="@android:color/white"
            android:layout_centerVertical="true"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <!--第一层次:底部输入框 和 消息显示框-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!--输入框紧贴底部-->
        <RelativeLayout
            android:id="@+id/re_input_view"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/bg_content"
            android:layout_alignParentBottom="true">
            <ImageView
                android:layout_marginLeft="10dp"
                android:id="@+id/input_voice"
                android:layout_centerVertical="true"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:background="@mipmap/voice" />
            <RelativeLayout
                android:id="@+id/send_more"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <ImageView
                    android:layout_marginRight="10dp"
                    android:layout_marginLeft="10dp"
                    android:id="@+id/more"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="@mipmap/more"
                    />
                <TextView
                    android:visibility="gone"
                    android:id="@+id/send"
                    android:layout_marginLeft="5dp"
                    android:layout_width="40dp"
                    android:layout_height="30dp"
                    android:text="@string/send"
                    android:background="@android:color/holo_blue_light"
                    android:textColor="@android:color/white"
                    android:gravity="center|center_vertical"/>
            </RelativeLayout>

            <ImageView
                android:layout_marginLeft="10dp"
                android:id="@+id/input_emotion"
                android:layout_toLeftOf="@id/send_more"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:background="@mipmap/emotion"
                android:layout_centerVertical="true"/>
            <cn.xie.imchat.view.MyEditTextView
                android:layout_toRightOf="@+id/input_voice"
                android:layout_toLeftOf="@+id/input_emotion"
                android:layout_centerVertical="true"
                android:layout_marginLeft="10dp"
                android:paddingLeft="5dp"
                android:id="@+id/input_text"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="@drawable/round_input_bg"
                android:gravity="center_vertical"
                />
        </RelativeLayout>
        <!--消息显示框紧贴输入框顶部-->
        <!--聊天内容-->
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_chat"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/re_input_view"
            android:overScrollMode="always">
        </androidx.recyclerview.widget.RecyclerView>
    </RelativeLayout>


</LinearLayout>

接下来就详细的给大家讲解逻辑处理以及相关优化

首先,是当输入框值不为空显示和为空的显示

如下面的两张图所示,当值为空时,显示+号,当值不为空时,显示发送按钮。
Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第2张图片Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第3张图片
要实现如上面的效果,除了布局要根据我之前给的那样,还需要在ChatActivity中进行逻辑的处理。

inputText = findViewById(R.id.input_text);
        inputText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //这里控制输入框里面没有值时显示+按钮,有值时显示发送按钮
                if (!TextUtils.isEmpty(s.toString())){
                    more.setVisibility(View.GONE);
                    send.setVisibility(View.VISIBLE);
                }else {
                    more.setVisibility(View.VISIBLE);
                    send.setVisibility(View.GONE);
                }
            }
        });
其次,如何控制当软件盘弹出来的时候,不遮住RecyclerView显示的消息内容

Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第4张图片
要让软件盘弹出的时候,不去遮住RecyclerView显示的消息内容,首先在AndroidManifest.xml对应的activity配置了android:windowSoftInputMode=“adjustResize”,

<activity android:name=".activity.ChatActivity"
            android:windowSoftInputMode="adjustResize"></activity>

//这里控制只要点击输入框就滚动到最底部
       inputText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                 recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (manager.findLastCompletelyVisibleItemPosition() < adapter.getItemCount() - 1) {
                    manager.setStackFromEnd(true);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    manager.setStackFromEnd(false);
                    recyclerView.setLayoutManager(manager);
                }
            }
        });
        if (chatMessageList.size() > 0) {
            recyclerView.smoothScrollToPosition(chatMessageList.size() - 1);
        }
            }
        });
再者,如何在刚进入ChatActivity的时候,定位到RecyclerView的最后一行

在设置适配器后,去判断是否铺满屏幕,没有铺满时把setStackFromEnd设为false,铺满时setStackFromEnd设为true:

chatMessageList = dbManager.queryHistoryChatMessageByName(sendName);
        adapter = new ChatAdapter(context,chatMessageList);
        recyclerView.setAdapter(adapter);
        //监听消息item是否铺满屏幕
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (manager.findLastCompletelyVisibleItemPosition() < adapter.getItemCount() - 1) {
                    manager.setStackFromEnd(true);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    manager.setStackFromEnd(false);
                    recyclerView.setLayoutManager(manager);
                }
            }
        });
        //定位到最底部
        if (chatMessageList.size() > 0) {
            recyclerView.smoothScrollToPosition(chatMessageList.size() - 1);
        }
又或,如何让接收或发送信息后也定位到最后一行

发送消息后新增了item,重新去判断是否铺满屏幕,没有铺满时把setStackFromEnd设为false,铺满时setStackFromEnd设为true

recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (manager.findLastCompletelyVisibleItemPosition() < adapter.getItemCount() - 1) {
                    manager.setStackFromEnd(true);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    manager.setStackFromEnd(false);
                    recyclerView.setLayoutManager(manager);
                }
            }
        });
        if (chatMessageList.size() > 0) {
            recyclerView.smoothScrollToPosition(chatMessageList.size() - 1);
            manager.setStackFromEnd(false);
            recyclerView.setLayoutManager(manager);
        }
并且,如何在浏览中间的信息时候点击输入框后自动滚动定位到最后
 //点击输入框时,滚动到最新消息
        inputText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //是否铺满屏幕监听
                recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (manager.findLastCompletelyVisibleItemPosition() < adapter.getItemCount() - 1) {
                    manager.setStackFromEnd(true);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    manager.setStackFromEnd(false);
                    recyclerView.setLayoutManager(manager);
                }
            }
        });
        if (chatMessageList.size() > 0) {
            recyclerView.smoothScrollToPosition(chatMessageList.size() - 1);
        }
            }
        });
在打开软件盘是消息铺满了屏幕但在关闭软件盘时又没有铺满屏幕时
//自定义textView的软件盘关闭监听,当关闭软件盘时需要重新去判断是否铺满屏幕,没有铺满时把setStackFromEnd设为false,铺满时setStackFromEnd设为true
 inputText.setOnKeyBoardHideListener(new MyEditTextView.OnKeyBoardHideListener() {
            @Override
            public void onKeyHide(int keyCode, KeyEvent event) {
                //是否铺满屏幕监听
                 recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (manager.findLastCompletelyVisibleItemPosition() < adapter.getItemCount() - 1) {
                    manager.setStackFromEnd(true);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    manager.setStackFromEnd(false);
                    recyclerView.setLayoutManager(manager);
                }
            }
        });
        if (chatMessageList.size() > 0) {
            recyclerView.smoothScrollToPosition(chatMessageList.size() - 1);
        }
            }
        });

最后给大家看看效果截图

1.刚进入ChatActivity时,只有一条消息(未铺满屏幕),消息显示到最上边,此时效果图:
Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第5张图片
2.此时点击下面的输入框,弹出软件盘,消息还是显示在最上面,此时效果图(未铺满屏幕):
Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第6张图片
3.此时关闭软件盘,由于消息未铺满屏幕,此时效果图:
Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第7张图片
4.多发一些消息,在测试在关闭软件盘时未铺满屏幕,打开软件盘时铺满屏幕的情况:

Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第8张图片
此时关闭软件盘,由于重新计算发现消息item并没有铺满屏幕,会把setStackFromEnd的值设为false,让其靠上显示:
Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第9张图片
当不管打开软件盘还是关闭软件盘消息都铺满了屏幕时,在输入框获取到焦点时会显示最新的item:
Android smack聊天输入框与RecyclerView的实现与兼容(ChatActivity界面布局)--优化_第10张图片

PS:由于聊天界面代码实在太多,这里附上整个ChatActivity的代码,大家有疑问可以随时留言。

package cn.xie.imchat.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.filter.StanzaTypeFilter;
import org.jivesoftware.smack.packet.Stanza;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.xie.imchat.R;
import cn.xie.imchat.adapter.ChatAdapter;
import cn.xie.imchat.config.XmppConnection;
import cn.xie.imchat.domain.ChatMessage;
import cn.xie.imchat.domain.ChatUser;
import cn.xie.imchat.utils.DBManager;
import cn.xie.imchat.utils.Util;
import cn.xie.imchat.view.MyEditTextView;

public class ChatActivity extends BaseActivity {
    private ImageView back, more;
    private Context context;
    private TextView chatName, send;
    private String sendName, type, userName;
    private DBManager dbManager;
    private ChatAdapter adapter;
    private RecyclerView recyclerView;
    private List<ChatMessage> chatMessageList;
    private MyEditTextView inputText;
    private StanzaListener packetListener;
    private Chat chat;
    private LinearLayoutManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        context = this;
        dbManager = new DBManager(context);
        Intent intent = getIntent();
        sendName = intent.getStringExtra("sendName");
        type = intent.getStringExtra("type");
        //创建个人聊天窗口
        String sendJid = sendName + "@xie-pc";
        userName = Util.getLoginInfo(context).getUserName();
        chat = XmppConnection.getInstance().getFriendChat(sendJid);
        initView();
        initData();
    }

    /**
     * 加载聊天记录
     */
    private void initData() {
        chatMessageList = dbManager.queryHistoryChatMessageByName(sendName);
        adapter = new ChatAdapter(context, chatMessageList);
        recyclerView.setAdapter(adapter);
        //是否铺满屏幕监听
        addOnGlobalLayoutItem();

    }


    /**
     * 初始化布局
     */
    private void initView() {
        recyclerView = findViewById(R.id.recycler_chat);
        manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        //禁止滑动,解决滑动冲突
        recyclerView.setNestedScrollingEnabled(false);

        back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        chatName = findViewById(R.id.chat_name);
        ChatUser chatUser = dbManager.queryChatUserByName(sendName);
        if (chatUser != null) {
            Util.showName(context, chatName, chatUser.getUserName(), chatUser.getNickName());
        }
        send = findViewById(R.id.send);
        more = findViewById(R.id.more);
        inputText = findViewById(R.id.input_text);
        inputText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //这里控制输入框里面没有值时显示+按钮,有值时显示发送按钮
                if (!TextUtils.isEmpty(s.toString())) {
                    more.setVisibility(View.GONE);
                    send.setVisibility(View.VISIBLE);
                } else {
                    more.setVisibility(View.VISIBLE);
                    send.setVisibility(View.GONE);
                }
            }
        });
 	//点击输入框时,滚动到最新消息
        inputText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //是否铺满屏幕监听
                addOnGlobalLayoutItem();
            }
        });
        //输入框获取焦点时监听(此时软件盘打开)
        inputText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //是否铺满屏幕监听
                addOnGlobalLayoutItem();
            }
        });
        //软件盘关闭监听
        inputText.setOnKeyBoardHideListener(new MyEditTextView.OnKeyBoardHideListener() {
            @Override
            public void onKeyHide(int keyCode, KeyEvent event) {
                //是否铺满屏幕监听
                addOnGlobalLayoutItem();
            }
        });

        //这里控制输入值的发送,当发送后清空输入框
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputMsg = inputText.getText().toString();
                sendChatMessageListener(inputMsg);
                inputText.setText("");
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler handlerInitData = new Handler() {
    };
    private Runnable task = new Runnable() {
        @Override
        public void run() {
            initData();
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                handlerInit.sendEmptyMessage(1);
                initPacket();
            }
        });
        thread.start();

    }

    @SuppressLint("HandlerLeak")
    private Handler handlerInit = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            handlerInitData.postDelayed(task, 1000);
        }
    };

    public void initPacket() {
        try {
            final Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    if (packetListener == null) {
                        packetListener = new StanzaListener() {
                            @Override
                            public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException, SmackException.NotLoggedInException {
                                setProcessPacket(packet);
                            }
                        };
                    }
                    XmppConnection.getInstance().addAsyncStanzaListener(packetListener, StanzaTypeFilter.MESSAGE);
                }
            });
            thread.start();
        } catch (Exception e) {
            Log.e("initPacket", e.toString());
        }
    }

    private void setProcessPacket(Stanza packet) {
        try {
            handlerInit.sendEmptyMessage(1);
        } catch (Exception e) {
            Log.e("setProcessPacket", e.toString());
        }
    }

    /**
     * 添加聊天消息的监听
     */
    private void sendChatMessageListener(String inputMsg) {
        //发送消息
        XmppConnection.getInstance().sendMessage(chat, null, inputMsg);
        List<ChatMessage> chatMessages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(userName, sendName, inputMsg, "OUT", Util.getNewDate(), null, type);
        chatMessages.add(chatMessage);
        dbManager.addChatMessageData(chatMessages);
        chatMessageList.add(chatMessage);
        adapter.notifyDataSetChanged();
        //是否铺满屏幕监听
        addOnGlobalLayoutItem();

    }

    /**
     * item是否铺满屏幕监听
     */
    private void addOnGlobalLayoutItem() {
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (manager.findLastCompletelyVisibleItemPosition() < adapter.getItemCount() - 1) {
                    manager.setStackFromEnd(true);
                    recyclerView.setLayoutManager(manager);
                    recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    manager.setStackFromEnd(false);
                    recyclerView.setLayoutManager(manager);
                }
            }
        });
        if (chatMessageList.size() > 0) {
            recyclerView.smoothScrollToPosition(chatMessageList.size() - 1);
        }
    }

}

你可能感兴趣的:(Android)