让两个并行listview实现同步滑动的代码
时间: 2023-12-09 22:04:32 浏览: 87
要让两个并行的ListView实现同步滑动,你可以在它们的OnScrollListener中添加相应的代码。下面是一个简单的示例代码:
```
listView1.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Do nothing
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// 计算ListView1的滚动距离
int scrollY = getScrollY(listView1);
// 将ListView1的滚动距离设置给ListView2
setScrollY(listView2, scrollY);
}
});
listView2.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Do nothing
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// 计算ListView2的滚动距离
int scrollY = getScrollY(listView2);
// 将ListView2的滚动距离设置给ListView1
setScrollY(listView1, scrollY);
}
});
// 获取ListView的滚动距离
private int getScrollY(ListView listView) {
View c = listView.getChildAt(0);
if (c == null) {
return 0;
}
int firstVisiblePosition = listView.getFirstVisiblePosition();
int top = c.getTop();
return -top + firstVisiblePosition * c.getHeight();
}
// 将滚动距离设置给ListView
private void setScrollY(ListView listView, int scrollY) {
int position = scrollY / listView.getHeight();
int top = -scrollY % listView.getHeight();
listView.setSelectionFromTop(position, top);
}
```
在这个示例代码中,我们分别给两个ListView设置了OnScrollListener,并在OnScroll方法中计算出了当前ListView的滚动距离。然后,我们将ListView1的滚动距离设置给了ListView2,将ListView2的滚动距离设置给了ListView1,从而实现了两个ListView的同步滑动。注意,我们在设置滚动距离时使用了setSelectionFromTop方法,这个方法可以将ListView滚动到指定的位置。
阅读全文