要實現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
會根據第一個的位置進行同步滾動。