效果图
导入依赖
implementation 'com.youth.banner:banner:2.1.0'
implementation 'com.github.bumptech.glide:glide:4.12.0'
如果要加载网络上的图片资源,要添加网络权限(如图)
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
android:usesCleartextTraffic="true"
在activity中写如下代码
<com.youth.banner.Banner
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="20dp"
app:layout_constraintTop_toTopOf="parent" />
核心代码块
banner = findViewById(R.id.banner);
stringList.add("https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/a6efce1b9d16fdfabf36882ab08f8c5495ee7b9f.jpg");
stringList.add("https://ss3.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/0824ab18972bd40797d8db1179899e510fb3093a.jpg");
stringList.add("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2647888545,3751969263&fm=224&gp=0.jpg");
banner.setAdapter(new BannerImageAdapter<String>(stringList) {
@Override
public void onBindView(BannerImageHolder holder, String data, int position, int size) {
//加载图片
Glide.with(holder.itemView)
.load(data)
.apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
.into(holder.imageView);
}
});
//设置指示点
banner.setIndicator(new CircleIndicator(this));
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Banner banner;
List<String> stringList = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
banner = findViewById(R.id.banner);
stringList.add("https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/a6efce1b9d16fdfabf36882ab08f8c5495ee7b9f.jpg");
stringList.add("https://ss3.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/0824ab18972bd40797d8db1179899e510fb3093a.jpg");
stringList.add("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2647888545,3751969263&fm=224&gp=0.jpg");
banner.setAdapter(new BannerImageAdapter<String>(stringList) {
@Override
public void onBindView(BannerImageHolder holder, String data, int position, int size) {
//加载图片
Glide.with(holder.itemView)
.load(data)
.apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
.into(holder.imageView);
}
});
//设置指示点
banner.setIndicator(new CircleIndicator(this));
}
}
如果对你有帮助,欢迎一键三连。
如有错误,恳请指正。
要么努力,要么放弃