首先先在Fragment中加入banner
<com.youth.banner.Banner
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="@+id/toolbar"
/>
然后在依赖中加入
implementation'com.youth.banner:banner:1.4.10'
//Glide框架依赖
implementation "com.github.bumptech.glide:glide:4.6.1"
方法中写入轮播图方法
public class Fragment2 extends Fragment {
private Banner banner;
private List<Integer> image=new ArrayList<>();
private List<String> title=new ArrayList<>();
private void initData() {
image.add(R.drawable.lb_four);
image.add(R.drawable.lb_first);
// image.add(R.drawable.lb_second);
// image.add(R.drawable.lb_three);
// image.add(R.drawable.lb_five);
title.add("圣诞节活动");
title.add("不一样的美");
title.add("夏季推荐");
title.add("家具打折");
title.add("手表上新");
}
private void initView() {
banner.setIndicatorGravity(BannerConfig.CENTER);
banner.setImageLoader(new MyImageLoader());
banner.setImages(image);
banner.setBannerAnimation(Transformer.Default);
banner.isAutoPlay(true);
banner.setBannerTitles(title);
banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
banner.setDelayTime(3000);
banner.setOnBannerListener(this::OnBannerClick);
banner.start();
}
public void OnBannerClick(int position) {
Toast.makeText(getActivity(), "你点了第" + (position + 1) + "张轮播图", Toast.LENGTH_SHORT).show();
}
private class MyImageLoader extends ImageLoader {
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =LayoutInflater.from(getActivity()).inflate(R.layout.fragment_1,container,false);
banner = view.findViewById(R.id.banner);
initData();
initView();
return view;
}