Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android資訊 >> Android UI 實現廣告 Banner 輪播效果

Android UI 實現廣告 Banner 輪播效果

編輯:Android資訊

前言

本文主要來分享一個Android UI開發中實現廣告Banner的輪播效果,因為Banner效果在Android應用中比較常見,所以我們也來嘗試實現以下。下圖是360影視大全的Android應用:

用紅框框住的那個效果就是小巫今天要分享的,先來思考一下會用到什麼控件?有什麼用戶體驗?

控件我們可能一下子就可以想到的自然是ViewPager,沒錯!用到的就是ViewPager,那麼它會有什麼用戶體驗呢,它可能有以下幾個體驗:

1. 間隔不停的切換圖片,指示器也跟著變

2. 點擊圖片可以跳轉到指定的頁面

如何實現?

布局開始著手

/BannerAutoScrollDemo/res/layout/banner.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="210dp" >

        <android.support.v4.view.ViewPager
            android:id="@+id/vp"
            android:layout_width="match_parent"
            android:layout_height="210dp" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="@drawable/shadow_article" >

            <TextView
                android:id="@+id/tv_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/author_layout"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="10dp"
                android:maxLines="2"
                android:text="3月4日"
                android:textColor="@color/white"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/author_layout"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_toRightOf="@+id/tv_date"
                android:maxLines="2"
                android:text="我和令計劃只是同姓"
                android:textColor="@color/white"
                android:textSize="18sp" />

            <RelativeLayout
                android:id="@+id/author_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginLeft="10dp"
                android:gravity="center_vertical"
                android:paddingBottom="20dp" >

                <TextView
                    android:id="@+id/tv_pre"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="文章選題來自"
                    android:textColor="@color/white"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/tv_topic_from"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/tv_pre"
                    android:text="阿宅的"
                    android:textColor="@color/white"
                    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"
                
                android:background="@drawable/dot_focused"
                android:visibility="invisible" />

            <View
                android:id="@+id/v_dot1"
                 
                android:visibility="invisible"/>

            <View
                android:id="@+id/v_dot2"
                 
                android:visibility="invisible"/>

            <View
                android:id="@+id/v_dot3"
                 
                android:visibility="invisible"/>

            <View
                android:id="@+id/v_dot4"
                
                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);
		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<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;
	}

}

源碼下載:http://download.csdn.net/detail/wwj_748/8498749

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved