android

android banner如何实现无限滚动

小樊
103
2024-06-15 15:23:31
栏目: 编程语言

要实现Android中的无限滚动广告栏,可以使用ViewPager和FragmentPagerAdapter来实现。下面是一个简单的示例代码:

  1. 创建一个BannerFragment用于显示广告内容:
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]);
    }
}
  1. 创建一个BannerAdapter用于管理BannerFragment:
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;
    }
}
  1. 在MainActivity中设置ViewPager和BannerAdapter:
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的当前项来实现无限滚动效果。

0
看了该问题的人还看了