fragment轮播图
时间: 2023-12-18 14:26:58 浏览: 116
Fragmeng图片轮播
在Android开发中,我们可以使用Fragment来实现轮播图。可以通过在Fragment中创建一个Banner对象,并设置适配器和指示器来实现轮播图的效果。具体实现可以参考以下步骤:
1.在Fragment中创建一个Banner对象,并在构造函数中初始化轮播图的图片资源。
2.在onCreateView()方法中,将轮播图添加到布局中,并设置适配器和指示器。
3.在适配器中,将图片资源设置到ImageView中,并返回View对象。
4.在指示器中,设置指示器的样式和位置。
以下是一个示例代码:
```
public class HomeFragment extends Fragment {
private final ArrayList<infoBean> banners;
public HomeFragment() {
banners = new ArrayList<>();
banners.add(new infoBean(R.drawable.v1));
banners.add(new infoBean(R.drawable.v2));
banners.add(new infoBean(R.drawable.v3));
banners.add(new infoBean(R.drawable.v4));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_home2, container, false);
Banner banner = inflate.findViewById(R.id.banner);
banner.addBannerLifecycleObserver(this)
.setAdapter(new BannerViewApapter(banners, this))
.setIndicator(new CircleIndicator(getContext()));
return inflate;
}
private static class BannerViewApapter extends RecyclerView.Adapter<BannerViewApapter.ViewHolder> {
private final List<infoBean> mData;
private final Context mContext;
public BannerViewApapter(List<infoBean> data, Context context) {
mData = data;
mContext = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_banner, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Glide.with(mContext).load(mData.get(position).getImageRes()).into(holder.imageView);
}
@Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
}
}
}
}
```
阅读全文