在Android應(yīng)用中使用BannerViewPager可以通過以下布局技巧:
<androidx.viewpager.widget.ViewPager
android:id="@+id/banner_viewpager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
public class BannerAdapter extends PagerAdapter {
private List<AdModel> mData;
public BannerAdapter(List<AdModel> data) {
mData = data;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_banner, container, false);
ImageView imageView = view.findViewById(R.id.iv_banner);
AdModel adModel = mData.get(position);
imageView.setImageResource(adModel.getImageResId());
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp">
<ImageView
android:id="@+id/iv_banner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
</LinearLayout>
ViewPager bannerViewPager = findViewById(R.id.banner_viewpager);
BannerAdapter bannerAdapter = new BannerAdapter(adList);
bannerViewPager.setAdapter(bannerAdapter);
// 啟動(dòng)自動(dòng)輪播
AutoPlayViewPager autoPlayViewPager = new AutoPlayViewPager(bannerViewPager);
autoPlayViewPager.start();
通過以上布局技巧,可以實(shí)現(xiàn)在Android應(yīng)用中使用BannerViewPager展示廣告或圖片,并實(shí)現(xiàn)自動(dòng)輪播的功能。