Android UI - 实现广告Banner轮播效果

Android UI - 实现广告Banner轮播效果

前言

本篇博客要分享的一个效果是实现广告Banner轮播效果,这个效果也比较常见,一些视频类应用就经常有,就拿360影视大全来举例吧:

Android UI - 实现广告Banner轮播效果_第1张图片


用红框框住的那个效果就是小巫今天要分享的,先来思考一下会用到什么控件?有什么用户体验?

控件我们可能一下子就可以想到的自然是ViewPager,没错!用到的就是ViewPager,那么它会有什么用户体验呢,它可能有以下几个体验:

1. 间隔不停的切换图片,指示器也跟着变

2. 点击图片可以跳转到指定的页面


如何实现?

布局开始着手

/BannerAutoScrollDemo/res/layout/banner.xml




    

        

        

            

            

            

                

                

                
            
        

        

            

            

            

            

            
        
    


一个ViewPager,下面五个指示点,注意每个点都有同样的样式,我们在style.xml中定义样式:

/BannerAutoScrollDemo/res/values/styles.xml

 


定义圆点图形资源

/BannerAutoScrollDemo/res/drawable/dot_normal.xml




    

    


/BannerAutoScrollDemo/res/drawable/dot_focused.xml




    

    


定义广告实体

/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 getBannerAd() {
		List adList = new ArrayList();

		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 imageViews;// 滑动的图片集合

	private List dots; // 图片标题正文的那些点
	private List 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 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();

		// 点
		dots = new ArrayList();
		dotList = new ArrayList();
		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);
		adViewPager.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) {
			
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			
		}

		@Override
		public void onPageSelected(int position) {
			currentItem = position;
			AdDomain adDomain = adList.get(position);
			tv_title.setText(adDomain.getTitle()); // 设置标题
			tv_date.setText(adDomain.getDate());
			tv_topic_from.setText(adDomain.getTopicFrom());
			tv_topic.setText(adDomain.getTopic());
			dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
			dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			oldPosition = position;
		}
	}

	private class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return adList.size();
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView iv = imageViews.get(position);
			((ViewPager) container).addView(iv);
			final AdDomain adDomain = adList.get(position);
			// 在这个方法里面设置图片的点击事件
			iv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 处理跳转逻辑
				}
			});
			return iv;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}

	}

	/**
	 * 轮播广播模拟数据
	 * 
	 * @return
	 */
	public static List getBannerAd() {
		List adList = new ArrayList();

		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;
	}

}

源码下载:http://download.csdn.net/detail/wwj_748/8498749



转载请注明:IT_xiao小巫
博客地址:http://blog.csdn.net/wwj_748
移动开发狂热者群:299402133

你可能感兴趣的:(【Android,UI效果锦集】,Android自定义组件)