实现步骤:
- 导入第三方banner库
- 如何使用github开源库
- 在build.gradle下导入banner库
//依赖banner
implementation ("io.github.youth5201314:banner:2.2.2")
- 编写banner页面
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
app:title="轮播图"
app:titleTextColor="@color/white"
android:background="@color/my_light_primary"
android:layout_height="wrap_content"/>
<com.youth.banner.Banner
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</androidx.appcompat.widget.LinearLayoutCompat>
- banner代码具体实现
public class MainActivity extends AppCompatActivity {
private Banner mBanner;
private List<BannerDataInfo> mBannerDataInfoList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
mBanner = findViewById(R.id.banner);
//添加banner数据
mBannerDataInfoList.add(new BannerDataInfo(R.mipmap.room_1, "这是客房一"));
mBannerDataInfoList.add(new BannerDataInfo(R.mipmap.room_2, "这是客房二"));
mBannerDataInfoList.add(new BannerDataInfo(R.mipmap.room_4, "这是客房三"));
mBannerDataInfoList.add(new BannerDataInfo(R.mipmap.room_5, "这是客房四"));
//设置适配器
mBanner.setAdapter(new BannerImageAdapter<BannerDataInfo>(mBannerDataInfoList) {
@Override
public void onBindView(BannerImageHolder holder, BannerDataInfo data, int position, int size) {
//设置数据
holder.imageView.setImageResource(data.getImg());
}
});
//添加生命周期观察者
mBanner.addBannerLifecycleObserver(this);
//设置指示器
mBanner.setIndicator(new CircleIndicator(this));
//banner点击事件
mBanner.setOnBannerListener(new OnBannerListener<BannerDataInfo>() {
@Override
public void OnBannerClick(BannerDataInfo data, int position) {
Toast.makeText(MainActivity.this, data.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
- 效果图