alwaystest / Blog

24 stars 2 forks source link

ListView第二坑 #5

Open alwaystest opened 8 years ago

alwaystest commented 8 years ago

ListView第二坑

标签(空格分隔): WeChat


最近做Android端的聊天App,一个小Demo,就是把之前实习学到的Java版Socket聊天室移植到Android上。

出了个BUG,困扰了我三天,还是暴露出我Debug能力欠缺的问题,另外尽信书不如无书。O(∩_∩)O哈哈~

参考书籍《第一行代码》,第三章里面有写了一个聊天App的界面。我个菜鸟,当然搬过来用喽。我的代码是这样实现的,应用的第一个界面是登陆界面,这里我只要求输入用户名,点击登录按钮就跳转到第二个Activity,直接显示聊天历史消息,而在第一个界面,监听输入框的回车键来调用登录按钮的Click事件。第二个Activity里面进入界面默认直接加载所有历史消息,然后设置将显示的数据定位到最后一行。此时BUG出现了:

于第一个Activity点击按钮登录第二个界面,显示正常。 但是使用回车键进入第二个界面,聊天记录就定位到了第一行,并且显示了一个Selected的状态。

刚开始处理了一个onKeyListener触发了两次点击按钮的BUG,导致我坚定的认为是焦点那里出了错误。网上找文章也没找到几个靠谱的,今天晚上灵光一现把MsgList的个数ListView.getSelectedItemPosition()打出来看了一下,果然发现问题了,msgListView.setSelection(msgContentList.size())之后,再调用msgListView.getSelectedItemPosition()显示是来居然是-1

其实原因在msgListView.setSelection(msgContentList.size())

官方说明是这样的

public void setSelection (int position) Added in API level 1 Sets the currently selected item. If in touch mode, the item will not be selected but it will still be positioned appropriately. If the specified selection position is less than 0, then the item at position 0 will be selected. Parameters position Index (starting at 0) of the data item to be selected.

所以把代码更正为msgListView.setSelection(msgContentList.size()-1)就好了。现在新的问题来了,用回车键登录以后,和鼠标点击登录有一点不同,回车以后ListView最后一条是亮的。

待修复%>_<%。