Android的ListView数据更新后,如何使最新的条目可以自动滚动到可视范围内?

来源:互联网 发布:wonder girls 知乎 编辑:程序博客网 时间:2024/05/17 03:35

在ListView的layout配置中添加 android:transcriptMode="alwaysScroll"

[html] view plaincopy
  1. <ListView  
  2.     android:id="@+id/listView"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:layout_alignParentLeft="true"  
  6.     android:transcriptMode="alwaysScroll"  
  7. </ListView>  

或者在Java代码中执行

[java] view plaincopy
  1. mListView = (ListView) view.findViewById(R.id.listview);  
  2.         mListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);  


 

当数据改变的时候,在回调函数中使用ListView.setSelection()方法来定位到最后一行

[java] view plaincopy
  1. ChatAdapter adapter = new ChatAdapter(this);  
  2.   
  3. ListView lv = (ListView) findViewById(R.id.chatList);  
  4. lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);  
  5. lv.setAdapter(adapter);  
  6.   
  7. adapter.registerDataSetObserver(new DataSetObserver() {  
  8.     @Override  
  9.     public void onChanged() {  
  10.         super.onChanged();  
  11.         lv.setSelection(adapter.getCount() - 1);      
  12.     }  
  13. });  


 PS:http://stackoverflow.com/questions/3606530/listview-scroll-to-the-end-of-the-list-after-updating-the-list

 


 


        ====================================================================================

  作者:欧阳鹏  欢迎转载,与人分享是进步的源泉!

  转载请保留原文地址:http://blog.csdn.net/ouyang_peng

====================================================================================



//--------------------------------------------------------------------------------

总结:上面的例子是不是非常想微信等聊天的ListView,当滑动到某条信息的时候,停留在滑到的位置,而当接收到新的消息或者发送了新的消息的时候,则自动滚动到最后一条数据。

0 0
原创粉丝点击