Android ListView向下滚动

问题描述:

我有一个服务中的媒体播放器,它发送消息给我的活动,其中托管一个ListView。假设我在ListView中有100首歌曲,并且每次选择歌曲时,该行的背景都会改变。我需要选中的行始终在屏幕上可见。我现在遇到的问题是,当前歌曲完成后,我的服务将转到下一首歌曲,并选择该行。但是,当所选歌曲在屏幕上不可见时,它不会向下滚动。当它检测到当前歌曲是用户可以在他的屏幕上看到的最后一首歌曲时,我需要它自动滚动。Android ListView向下滚动

这是我的XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="?android:attr/activatedBackgroundIndicator" > 

    <TextView 
    android:id="@+id/txt_song" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

    <TextView 
    android:id="@+id/txt_singer" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/txt_song" /> 
</RelativeLayout> 

下面从我的活动代码。我在服务类中有一个处理程序,当歌曲完成并发送到下一首歌曲时,会向该活动发送一条消息。

private void updateUI(Intent serviceIntent){ 
    int songPos = serviceIntent.getIntExtra("songpos", 0); 
    mListSongs.setItemChecked(songPos, true); 
    //mListSongs.setSelection(songPos); 
} 

如果我使用mListSongs.setSelection(songPos),这首歌总是会在顶部选择,但是这不是我想要的。

您可以使用ListView.smoothScrollToPosition()

该视图将滚动显示指定的位置。

private void updateUI(Intent serviceIntent){ 
    int songPos = serviceIntent.getIntExtra("songpos", 0); 
    mListSongs.setItemChecked(songPos, true); 
    mListSongs.smoothScrollToPosition(songPos); 
}