就像在聊天应用程序中,每当我们想要发送消息时,软键盘弹出窗口也会自动滚动最后看到的消息到软键盘的顶部,前提是没有任何东西隐藏在软键盘后面。但在我的情况下,键盘隐藏了对话。如何解决这个问题,我已经使用了显示消息的回收站视图。我用的是android.support.v7.widget.RecyclerView
使用RecyclerView,您可以实现以下操作:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(linearLayoutManager);
这段代码会告诉RecyclerView相对于列表底部滚动,但它也会以相反的顺序显示消息,所以在你的代码中,如果你从数据库中获取消息,从最后一条消息中读取它们,像这样:
Cursor c = ...;
c.moveToLast();
do{
//your code which gets messages from cursor...
}while(c.moveToPrevoius());
,当你想添加新消息到列表时,只需像这样添加它们:
//ArrayList messages
messages.add(0, message);
我如何处理这个很简单,实现一个良好的行为,类似于Whatsapp或其他流行的聊天工具。
首先,像这样设置LinearLayoutManager
。
new LinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, true);
chatLayoutManager.setStackFromEnd(true);
当消息开始溢出底部的RecyclerView
时,需要将当前位置设置为0,为了实现这一点,一个简单的界面就像一个魅力一样,在RecyclerView.Adapter
呈现最后一条消息时发出警告。
public interface OnLastItemRendered{
void lastItemRendered();
}
将接口实现从活动/片段传递给de RecyclerView.Adapter
,以调用RecyclerView
中的scrollToPosition
。
new ChatMessageListAdapter(
context, user, lastOldMessages,
new OnLastItemRendered() {
@Override
public void lastItemRendered() {
ContainerFragment.this.myRecyclerViewToChat.scrollToPosition(0);
}
});
最后,如果想在RecyclerView
中执行动画,实现一个方法将RecyclerView.Adapter
中的消息添加到notifyItemInserted
方法中。
public void add(ChatMessage chatMessage) {
if (this.chatMessages == null) {
this.chatMessages = new ArrayList<ChatMessage>();
}
this.chatMessages.add(chatMessage);
Collections.sort(this.chatMessages, this.orderChatMessagesComparator);
this.notifyItemInserted(0);
this.onLastItemRendered.lastItemRendered();
}
对于开始加载的X消息,在onBindViewHolder
.
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ChatMessage currentMessage = this.chatMessages.get(position);
... //Do your stuff.
if (position == 0) this.onLastItemRendered.lastItemRendered();
}
工作。
您可以检测编辑文本的焦点,如果您的editText有焦点,滚动你的recyclerView列表到最后一个元素
private OnFocuseChangeListener focuseListener = new OnFocuseChangeListener(){
public void onFocusChange(View v, boolean hasFocus){
if(hasFocus){
// Scroll down to the last element of the list
recyclerView.scrollToPosition(sizeOfYourList);
} else {
focusedView = null;
}
}
}
同样,当您单击发送按钮或想要显示列表的最后一个元素时,使用scrolltopposition ()