SliderLayout实现轮播图
源码地址:https://github.com/Bacsonlx/Android-CNiaoShop/tree/master/CNiaoShop_03
(注:代码采用的是第一章的模板,关于轮播图的代码只需要看HomeFragment以及相关的布局文件即可 )
效果图:
一、AndroidImageSlider简介
AndroidImageSlider是GitHub上的一个非常火的开源项目,由“代码家”出品,他的网址是https://github.com/daimajia/AndroidImageSlider。下面的用法介绍很多都是参考他的GitHub主页的常规用法,因此建议大家学习使用开源项目的时候直接参考GitHub主页的用法介绍。
下图是AndroidImageSlider的架构,最核心的类是SliderLayout,他继承自相对布局,包含了可以左右滑动切换的SliderView,以及页面指示器PagerIndicator,也就是上图中的4个小圆点。这两个都可以自定义,常规的用法是:使用TextSliderView+自定义PagerIndicator,下面对常规用法就行介绍。
二、AndroidImageSlider实现广告轮播条
1、添加依赖性和权限
参考GithHub中AndroidImageSlider主页的介绍,首先将需要的三个依赖项目引入进来,他们分别是:
dependencies {
implementation "com.android.support:support-v4:+"
implementation 'com.squareup.picasso:picasso:2.3.2'
implementation 'com.nineoldandroids:library:2.4.0'
implementation 'com.daimajia.slider:library:1.1.5@aar'
}
建议全部的依赖项目统一使用最新的版本,因为依赖的项目之间可能也会存在依赖,如果不想出现版本冲突问题,最后全部使用最新版。
添加权限:
<!-- if you want to load images from the internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- if you want to load images from a file OR from the internet -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2、布局文件
在布局文件中放置SliderLayout以及PagerIndicator。注意布局中是通过相对布局把PagerIndicator压在SliderLayout之上的。代码都可以在GitHub上找到参考。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 定义SliderLayout -->
<com.daimajia.slider.library.SliderLayout
android:id="@+id/slider"
android:layout_width