android - 如何实现聊天屏式软键盘行为?
问题描述
我试图在示例聊天应用程序中实现特定的键盘行为,在该应用程序中,当用户打开键盘时,键盘RecyclerView
会随键盘上升,但前提是最后一个聊天可见。
示例:在WhatsApp
打开键盘时,当最后一条消息可见时,列表将随键盘一起上升,以便对用户保持可见。现在向上滚动一点,然后打开键盘,现在列表将保持原样,不会随着键盘上升。
解决方案
为了实现与键盘一起向上滚动列表的行为,我从这里得出了解决方案:https ://stackoverflow.com/a/34103263/1739882
并添加决定是否滚动列表的自定义行为,我使用以下方法获取了最后一个可见项目:
linearLayoutManager.findLastVisibleItemPosition()
并使用标志来处理场景。这是完整的代码:
//Setup editText behavior for opening soft keyboard
activityChatHeadBinding.edtMsg.setOnTouchListener((v, event) -> {
InputMethodManager keyboard = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (keyboard != null) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) activityChatHeadBinding.recyclerView.getLayoutManager();
isScrollToLastRequired = linearLayoutManager.findLastVisibleItemPosition() == chatNewAdapter.getItemCount() - 1;
keyboard.showSoftInput(findViewById(R.id.layout_send_msg), InputMethodManager.SHOW_FORCED);
}
return false;
});
//Executes recycler view scroll if required.
activityChatHeadBinding.recyclerView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
if (bottom < oldBottom && isScrollToLastRequired) {
activityChatHeadBinding.recyclerView.postDelayed(() -> activityChatHeadBinding.recyclerView.scrollToPosition(
activityChatHeadBinding.recyclerView.getAdapter().getItemCount() - 1), 100);
}
});
推荐阅读
- codenameone - 自定义 iOS VKB 工具栏
- javascript - 优化 EmEditor 宏以对单个列和提取计数进行元素排序、拆分和重复数据删除
- java - Java - !String.equals("abc") 在应该为 FALSE 时返回 TRUE
- image - SSL附加后的Opencart图像问题
- anaconda - 为什么anaconda在创建新环境时会重新下载我已经拥有的包?
- python - 如何为熊猫数据框添加标题
- xcode - 有没有办法修复滚动
- mongodb - Mongodb $lookup 与聚合查询中的条件
- react-native - 子组件更新时更改父状态
- vue.js - Electron JS事件多次触发