可以通过使用ViewPager和PagerAdapter来实现自动横向滚动视图的无限循环滚动。具体步骤如下:
创建一个包含所有要显示的视图的ArrayList。
创建一个无限循环滚动适配器,在适配器的构造函数中将ArrayList复制到一个新的ArrayList中,并在原始ArrayList的末尾再添加一次这个新的ArrayList(确保所有视图都会无限循环)。
public class InfiniteScrollViewPagerAdapter extends PagerAdapter {
private ArrayList views = new ArrayList<>();
public InfiniteScrollViewPagerAdapter(ArrayList views) {
this.views.addAll(views);
this.views.addAll(new ArrayList<>(views)); // 复制一遍views,相当于两倍长度,从而实现无限循环
}
@Override
public int getCount() {
return Integer.MAX_VALUE; // 返回Integer.MAX_VALUE,相当于无限个视图,从而实现无限循环
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View view = views.get(position % views.size());
container.addView(view);
return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
public class MainActivity extends AppCompatActivity {
private ArrayList views = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
views.add(getLayoutInflater().inflate(R.layout.view_item, null));
views.add(getLayoutInflater().inflate(R.layout.view_item, null));
views.add(getLayoutInflater().