溫馨提示×

android banner如何實現(xiàn)無限滾動

小樊
103
2024-06-15 15:23:31
欄目: 編程語言

要實現(xiàn)Android中的無限滾動廣告欄,可以使用ViewPager和FragmentPagerAdapter來實現(xiàn)。下面是一個簡單的示例代碼:

  1. 創(chuàng)建一個BannerFragment用于顯示廣告內(nèi)容:
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. 創(chuàng)建一個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中設(shè)置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);

        // 設(shè)置一個定時器來輪播廣告
        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);
    }
}

這樣就可以實現(xiàn)一個簡單的無限滾動廣告欄,通過不斷切換ViewPager的當(dāng)前項來實現(xiàn)無限滾動效果。

0