要实现Android滚动控件的同步滚动,可以使用OnScrollListener
接口来监听滚动事件,然后通过scrollTo()
或scrollBy()
方法来控制其他滚动控件的滚动位置。
以下是一个示例代码,实现了两个ListView
控件的同步滚动:
public class SyncedScrollActivity extends AppCompatActivity {
private ListView listView1;
private ListView listView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_synced_scroll);
listView1 = findViewById(R.id.listView1);
listView2 = findViewById(R.id.listView2);
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.items));
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.items));
listView1.setAdapter(adapter1);
listView2.setAdapter(adapter2);
listView1.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
listView2.setSelectionFromTop(firstVisibleItem, 0);
}
});
listView2.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
listView1.setSelectionFromTop(firstVisibleItem, 0);
}
});
}
}
在上面的代码中,我们分别为两个ListView
控件设置了相同的滚动监听器,当一个ListView
滚动时,另一个ListView
会根据第一个的位置进行同步滚动。