Android UI - 实现广告 Banner 轮播效果,Android 大厂 74 道高级面试合集
android:textSize="12sp" />
<TextView
android:id="@+id/tv_topic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@+id/tv_topic_from"
android:text="“我想知道令狐安和令计划有什么关系?”"
android:textColor="@color/white"
android:textSize="12sp" />
</RelativeLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="10dp"
android:gravity="center" >
<View
android:id="@+id/v_dot0"
style="@style/dot_style"
android:background="@drawable/dot_focused"
android:visibility="invisible" />
<View
android:id="@+id/v_dot1"
style="@style/dot_style"
android:visibility="invisible"/>
<View
android:id="@+id/v_dot2"
style="@style/dot_style"
android:visibility="invisible"/>
<View
android:id="@+id/v_dot3"
style="@style/dot_style"
android:visibility="invisible"/>
<View
android:id="@+id/v_dot4"
style="@style/dot_style"
android:visibility="invisible" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
一个 ViewPager,下面五个指示点,注意每个点都有同样的样式,我们在 style.xml 中定义样式:
/BannerAutoScrollDemo/res/values/styles.xml
<style name="dot_style">
<item name="android:layout_width">5dip</item>
<item name="android:layout_height">5dip</item>
<item name="android:background">@drawable/dot_normal</item>
<item name="android:layout_marginLeft">1.5dip</item>
<item name="android:layout_marginRight">1.5dip</item>
</style>
定义圆点图形资源
/BannerAutoScrollDemo/res/drawable/dot_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#33000000" />
<corners android:radius="5dip" />
</shape>
/BannerAutoScrollDemo/res/drawable/dot_focused.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#aaFFFFFF" />
<corners android:radius="5dip" />
</shape>
定义广告实体
/BannerAutoScrollDemo/src/com/xiaowu/banner/demo/AdDomain.java
package com.xiaowu.banner.demo;
/**
广告实体
@author wwj_748
*/
public class AdDomain {
private String id; // 广告 id
private String date; // 日期
private String title; // 标题
private String topicFrom; //选题来自
private String topic; // 选题
private String imgUrl; // 图片 url
private boolean isAd; // 是否为广告
private String startTime; // 广告开始时间
private String endTime; // 广告结束时间
private String targetUrl; // 目标 url
private int width; // 宽
private int height; // 高
private boolean available; // 是否可用
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public boolean isAd() {
return isAd;
}
public void setAd(boolean isAd) {
this.isAd = isAd;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getTopicFrom() {
return topicFrom;
}
public void setTopicFrom(String topicFrom) {
this.topicFrom = topicFrom;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getTargetUrl() {
return targetUrl;
}
public void setTargetUrl(String targetUrl) {
this.targetUrl = targetUrl;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
实现切换逻辑
1. 定时切换
2. 切换图片
3. 切换标题
4. 切换指示器
定时切换用到一个类:ScheduledExecutorService
作用是定时执行任务,我们这里要做的定时任务是,2 秒执行一次图片切换
private void startAd() {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// 当 Activity 显示出来后,每两秒切换一次图片显示
scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2,
TimeUnit.SECONDS);
}
定义子线程
private class ScrollTask implements Runnable {
@Override
public void run() {
synchronized (adViewPager) {
currentItem = (currentItem + 1) % imageViews.size();
handler.obtainMessage().sendToTarget();
}
}
}
通过 handle 来通知 ViewPager 进行视图切换
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
adViewPager.setCurrentItem(currentItem);
};
};
我们提供模拟数据来进行测试
/**
轮播广播模拟数据
@return
*/
public static List<AdDomain> getBannerAd() {
List<AdDomain> adList = new ArrayList<AdDomain>();
AdDomain adDomain = new AdDomain();
adDomain.setId("108078");
adDomain.setDate("3 月 4 日");
adDomain.setTitle("我和令计划只是同姓");
adDomain.setTopicFrom("阿宅");
adDomain.setTopic("我想知道令狐安和令计划有什么关系?");
adDomain.setImgUrl("http://g.hiphotos.baidu.com/image/w%3D310/sign=bb99d6add2c8a786be2a4c0f5708c9c7/d50735fae6cd7b8900d74cd40c2442a7d9330e29.jpg");
adDomain.setAd(false);
adList.add(adDomain);
AdDomain adDomain2 = new AdDomain();
adDomain2.setId("108078");
adDomain2.setDate("3 月 5 日");
adDomain2.setTitle("我和令计划只是同姓");
adDomain2.setTopicFrom("小巫");
adDomain2.setTopic("“我想知道令狐安和令计划有什么关系?”");
adDomain2
.setImgUrl("http://g.hiphotos.baidu.com/image/w%3D310/sign=7cbcd7da78f40ad115e4c1e2672e1151/eaf81a4c510fd9f9a1edb58b262dd42a2934a45e.jpg");
adDomain2.setAd(false);
adList.add(adDomain2);
AdDomain adDomain3 = new AdDomain();
adDomain3.setId("108078");
adDomain3.setDate("3 月 6 日");
adDomain3.setTitle("我和令计划只是同姓");
adDomain3.setTopicFrom("旭东");
adDomain3.setTopic("“我想知道令狐安和令计划有什么关系?”");
adDomain3
.setImgUrl("http://e.hiphotos.baidu.com/image/w%3D310/sign=392ce7f779899e51788e3c1572a6d990/8718367adab44aed22a58aeeb11c8701a08bfbd4.jpg");
adDomain3.setAd(false);
adList.add(adDomain3);
AdDomain adDomain4 = new AdDomain();
adDomain4.setId("108078");
adDomain4.setDate("3 月 7 日");
adDomain4.setTitle("我和令计划只是同姓");
adDomain4.setTopicFrom("小软");
adDomain4.setTopic("“我想知道令狐安和令计划有什么关系?”");
adDomain4
.setImgUrl("http://d.hiphotos.baidu.com/image/w%3D310/sign=54884c82b78f8c54e3d3c32e0a282dee/a686c9177f3e670932e4cf9338c79f3df9dc55f2.jpg");
adDomain4.setAd(false);
adList.add(adDomain4);
AdDomain adDomain5 = new AdDomain();
adDomain5.setId("108078");
adDomain5.setDate("3 月 8 日");
adDomain5.setTitle("我和令计划只是同姓");
adDomain5.setTopicFrom("大熊");
adDomain5.setTopic("“我想知道令狐安和令计划有什么关系?”");
adDomain5
.setImgUrl("http://e.hiphotos.baidu.com/image/w%3D310/sign=66270b4fe8c4b7453494b117fffd1e78/0bd162d9f2d3572c7dad11ba8913632762d0c30d.jpg");
adDomain5.setAd(true); // 代表是广告
adList.add(adDomain5);
return adList;
}
ViewPager 逻辑处理
1. 填充数据(自定义 Adapter)
2. 设置页面切换监听事件
3. 在自定义 adapter 中的 instantiateItem 方法设置 ViewPager 点击事件
这里我们的图片是从网上下载的,用到了 universal-image-loader-1.8.6-with-sources.jar 这个类库,可以实现异步加载图片,具体使用查看代码。
最后给出完整代码:
/BannerAutoScrollDemo/src/com/xiaowu/banner/demo/MainActivity.java
package com.xiaowu.banner.demo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
public class MainActivity extends Activity {
public static String IMAGE_CACHE_PATH = "imageloader/Cache"; // 图片缓存路径
private ViewPager adViewPager;
private List<ImageView> imageViews;// 滑动的图片集合
private List<View> dots; // 图片标题正文的那些点
private List<View> dotList;
private TextView tv_date;
private TextView tv_title;
private TextView tv_topic_from;
private TextView tv_topic;
private int currentItem = 0; // 当前图片的索引号
// 定义的五个指示点
private View dot0;
private View dot1;
private View dot2;
private View dot3;
private View dot4;
// 定时任务
private ScheduledExecutorService scheduledExecutorService;
// 异步加载图片
private ImageLoader mImageLoader;
private DisplayImageOptions options;
// 轮播 banner 的数据
private List<AdDomain> adList;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
adViewPager.setCurrentItem(currentItem);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 使用 ImageLoader 之前初始化
initImageLoader();
// 获取图片加载实例
mImageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.top_banner_android)
.showImageForEmptyUri(R.drawable.top_banner_android)
.showImageOnFail(R.drawable.top_banner_android)
.cacheInMemory(true).cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.EXACTLY).build();
initAdData();
startAd();
}
/**
初始化 ImageLoader
*/
private void initImageLoader() {
File cacheDir = com.nostra13.universalimageloader.utils.StorageUtils
.getOwnCacheDirectory(getApplicationContext(),
IMAGE_CACHE_PATH);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisc(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions)
.memoryCache(new LruMemoryCache(12 * 1024 * 1024))
.memoryCacheSize(12 * 1024 * 1024)
.discCacheSize(32 * 1024 * 1024).discCacheFileCount(100)
.discCache(new UnlimitedDiscCache(cacheDir))
.threadPriority(Thread.NORM_PRIORITY - 2)
.tasksProcessingOrder(QueueProcessingType.LIFO).build();
ImageLoader.getInstance().init(config);
}
/**
初始化广告数据
*/
private void initAdData() {
// 广告数据
adList = getBannerAd();
imageViews = new ArrayList<ImageView>();
// 点
dots = new ArrayList<View>();
dotList = new ArrayList<View>();
dot0 = findViewById(R.id.v_dot0);
dot1 = findViewById(R.id.v_dot1);
dot2 = findViewById(R.id.v_dot2);
dot3 = findViewById(R.id.v_dot3);
dot4 = findViewById(R.id.v_dot4);
dots.add(dot0);
dots.add(dot1);
dots.add(dot2);
dots.add(dot3);
dots.add(dot4);
tv_date = (TextView) findViewById(R.id.tv_date);
tv_title = (TextView) findViewById(R.id.tv_title);
tv_topic_from = (TextView) findViewById(R.id.tv_topic_from);
tv_topic = (TextView) findViewById(R.id.tv_topic);
adViewPager = (ViewPager) findViewById(R.id.vp);
adVie
wPager.setAdapter(new MyAdapter());// 设置填充 ViewPager 页面的适配器
// 设置一个监听器,当 ViewPager 中的页面改变时调用
adViewPager.setOnPageChangeListener(new MyPageChangeListener());
addDynamicView();
}
private void addDynamicView() {
// 动态添加图片和下面指示的圆点
// 初始化图片资源
for (int i = 0; i < adList.size(); i++) {
ImageView imageView = new ImageView(this);
// 异步加载图片
mImageLoader.displayImage(adList.get(i).getImgUrl(), imageView,
options);
imageView.setScaleType(ScaleType.CENTER_CROP);
imageViews.add(imageView);
dots.get(i).setVisibility(View.VISIBLE);
dotList.add(dots.get(i));
}
}
@Override
protected void onResume() {
super.onResume();
}
private void startAd() {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// 当 Activity 显示出来后,每两秒切换一次图片显示
scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2,
TimeUnit.SECONDS);
}
private class ScrollTask implements Runnable {
@Override
public void run() {
synchronized (adViewPager) {
currentItem = (currentItem + 1) % imageViews.size();
handler.obtainMessage().sendToTarget();
}
}
}
@Override
protected void onStop() {
super.onStop();
// 当 Activity 不可见的时候停止切换
scheduledExecutorService.shutdown();
}
private class MyPageChangeListener implements OnPageChangeListener {
private int oldPosition = 0;
@Override
public void onPageScrollStateChanged(int arg0) {
评论