做了很多的App,发现广告Banner非常的常用,在这里就总结一下我的做法,先看看一个应用的广告Banner
1. ViewPager中展示和下载图片
下面我们来实现一个类似的广告Banner,主布局界面
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
tools:context=".MyBannerActivity">
<com.example.liuwangshu.mybanner.SlideShowView
android:id="@+id/sv_photo"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="@android:color/darker_gray" />
</RelativeLayout>
在布局里引用了com.example.liuwangshu.mybanner.SlideShowView,这是自定义布局,继承FrameLayout,用来展示轮播图片和圆点。
SlideShowView构造函数为
public SlideShowView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this,
true);
imageViewsList = new ArrayList<ImageView>();
dotViewsList = new ArrayList<View>();
}
加载了布局文件,并且创建了两个List,分别存储图片和小圆点。
布局文件layout_slideshow.xml,里面定义了ViewPager用来显示图片,其他的用来显示圆点
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout android:id="@+id/dotLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:gravity="right"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<View
android:id="@+id/v_dot1"
android:layout_width="8dp"
android:layout_height="8dp"
android:background="@drawable/dot_focus" />
<View
android:id="@+id/v_dot2"
android:layout_width="8dp"
android:layout_height="8dp"
android:layout_marginLeft="5dp"
android:background="@drawable/dot_blur" />
</LinearLayout>
</RelativeLayout>
这个自定义SlideShowView的核心方法为setView方法,用来接收将Activity传来imageUrls数组,初始化UI和实现轮播效果
public void setView(String[] imageUrls) {
this.imageUrls = imageUrls;
initUI(context);
if (isAutoPlay) {
startPlay();
}
}
startPlay方法我后面会讲解到,先来看看initUI方法,这个方法通过一个for循环将轮播需要的图片地址填充到imageViewsList中,将需要的小圆点填充到dotViewsList,并创建了viewPager将imageViewsList传进去展示轮播图。
private void initUI(Context context) {
if (imageUrls == null || imageUrls.length == 0)
return;
if (dotLayout != null) {
dotLayout.removeAllViews();
} else {
dotL