要實現Android中的無限滾動廣告欄,可以使用ViewPager和FragmentPagerAdapter來實現。下面是一個簡單的示例代碼:
public class BannerFragment extends Fragment {
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3};
private int currentPosition = 0;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_banner, container, false);
ImageView imageView = view.findViewById(R.id.banner_image);
imageView.setImageResource(images[currentPosition]);
return view;
}
public void nextBanner() {
currentPosition++;
if (currentPosition >= images.length) {
currentPosition = 0;
}
ImageView imageView = getView().findViewById(R.id.banner_image);
imageView.setImageResource(images[currentPosition]);
}
}
public class BannerAdapter extends FragmentPagerAdapter {
public BannerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new BannerFragment();
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
}
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private BannerAdapter bannerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
bannerAdapter = new BannerAdapter(getSupportFragmentManager());
viewPager.setAdapter(bannerAdapter);
// 設置一個定時器來輪播廣告
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
int currentItem = viewPager.getCurrentItem();
viewPager.setCurrentItem(currentItem + 1);
}
});
}
}, 0, 3000);
}
}
這樣就可以實現一個簡單的無限滾動廣告欄,通過不斷切換ViewPager的當前項來實現無限滾動效果。