在Android应用中使用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);
// 启动自动轮播
AutoPlayViewPager autoPlayViewPager = new AutoPlayViewPager(bannerViewPager);
autoPlayViewPager.start();
通过以上布局技巧,可以实现在Android应用中使用BannerViewPager展示广告或图片,并实现自动轮播的功能。