Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android首頁輪播圖直接拿來用

Android首頁輪播圖直接拿來用

編輯:關於Android編程

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.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class HeadAD extends RelativeLayout {
	private ViewPager vp;
	private LinearLayout symbolLayout, bottomLayout;
	private LayoutParams lp;
	// private ArrayList symbolViews;
	private List showResults;
	private boolean isContinue = true;
	private int currentItem = 0; // 當前圖片的索引號

	private ScheduledExecutorService updateService;

	private Context context;

	public void initData(List pResult) {
		showResults = pResult;
	}

	public HeadAD(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		// setBackgroundResource(R.color.black);

	}

	public void initView(Context context) {
		// TODO Auto-generated method stub

		lp = new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(
				context, 180));
		vp = new ViewPager(context);
		vp.setLayoutParams(lp);

		lp = new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(
				context, 20));

		lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		bottomLayout = new LinearLayout(context);
		bottomLayout.setGravity(Gravity.CENTER);
		bottomLayout.setOrientation(LinearLayout.VERTICAL);
		bottomLayout.setLayoutParams(lp);
		bottomLayout.setBackgroundResource(R.color.footerBg);

		lp = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		symbolLayout = new LinearLayout(context);
		symbolLayout.setGravity(Gravity.CENTER);
		symbolLayout.setOrientation(LinearLayout.HORIZONTAL);
		symbolLayout.setPadding(0, 0, 5, 5);

		ImageView symbolIv;
		for (int i = 0; i < showResults.size(); i++) {
			if (showResults.size() > 1) {
				symbolIv = new ImageView(context);
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT,
						LinearLayout.LayoutParams.WRAP_CONTENT);

				params.rightMargin = 10;
				symbolIv.setBackgroundResource(R.drawable.point_bg);
				symbolIv.setEnabled(false);
				if (i == 0) {
					symbolIv.setEnabled(true);
				} else {
					symbolIv.setEnabled(false);
				}
				symbolIv.setLayoutParams(params);
				symbolLayout.addView(symbolIv);
			}

		}
		bottomLayout.addView(symbolLayout);
		adapter = new ViewPagerAdapter(context, showResults);
		vp.setAdapter(adapter);
		vp.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					isContinue = false;
					break;
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
					break;
				case MotionEvent.ACTION_CANCEL:
					break;
				}
				return false;
			}
		});
		vp.setOnPageChangeListener(new MyPageChangeListener());
		addView(vp);
		addView(bottomLayout);

	}

	private Handler viewPagerHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			vp.setCurrentItem(currentItem % showResults.size());// 切換當前顯示的圖片
		};
	};
	public ViewPagerAdapter adapter;

	// 直接在activity的OnResume裡調用,當前界面是該activity時開始循環

	public void startUpdate() {
		this.updateService = Executors.newSingleThreadScheduledExecutor();

		this.updateService.scheduleAtFixedRate(new ScrollTask(), 5, 5,
				TimeUnit.SECONDS);

	}

	// 直接在activity的OnPause裡調用,當前界面不是該activity時停止循環

	public void stopUpdate() {
		this.updateService.shutdown();
		updateService = null;
	}

	/**
	 * 當ViewPager中頁面的狀態發生改變時調用
	 * 
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		public void onPageSelected(int position) {
			currentItem = position % showResults.size();
			symbolLayout.getChildAt(oldPosition).setEnabled(false);
			symbolLayout.getChildAt(position).setEnabled(true);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

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

		}
	}

	/**
	 * 換行切換任務
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			if (isContinue) {
				synchronized (vp) {
					System.out.println("currentItem: " + currentItem);
					currentItem = (currentItem + 1) % showResults.size();
					viewPagerHandler.obtainMessage().sendToTarget(); // 通過Handler切換圖片
				}
			}
		}

	}

}

HEADAD 實現了自定輪播計時。

下面看adapter寫法 刪除了部分項目邏輯

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;


import com.nostra13.universalimageloader.core.DisplayImageOptions;

/*******************************************************
 * 
 * 
 ********************************************************/
public class ViewPagerAdapter extends PagerAdapter {

	List lists;
	Context ct;
	private ImageView imgView;
	private int currentPosition = 0;
	private DisplayImageOptions options;

	public ViewPagerAdapter(Context ct, List mList) {
		lists = mList;
		this.ct = ct;
		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisk(true)
				.showImageOnLoading(R.drawable.default_news_logo).build();
	}

	/**
	 * 獲得頁面的總數
	 */
	public int getCount() {
		return lists.size();
	}

	/**
	 * 獲得相應位置上的view container view的容器
	 */
	public Object instantiateItem(ViewGroup container, final int position) {
		// imgView.setOnClickListener(this);

		imgView = new ImageView(ct);

		imgView.setScaleType(ImageView.ScaleType.FIT_XY);
		if (lists.size() == 0) {

		} else {
			//寫自己的邏輯
			currentPosition = position % lists.size();

			
		}
		

		// 給 container 添加一個view
		container.addView(imgView);
		// 返回一個和該view相對的object
		return imgView;
	}

	/**
	 * 判斷 view和object的對應關系
	 */
	public boolean isViewFromObject(View view, Object object) {
		if (view == object) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 銷毀對應位置上的object
	 */
	public void destroyItem(ViewGroup container, int position, Object object) {

		container.removeView((View) object);
		object = null;
	}

	@Override
	public int getItemPosition(Object object) {
		// TODO Auto-generated method stub
		return super.getItemPosition(object);
	}

}
實體bean這裡就不貼了

用到工具類 ......還有幾個不重要就不貼了

import android.content.Context;

public class DensityUtil {
	/**
	 * 根據手機的分辨率從 dip 的單位 轉成為 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根據手機的分辨率從 px(像素) 的單位 轉成為 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

}



如何調用:

mViewPager = new HeadAD(getActivity(), null);
		mViewPager.initData(viewPagerLists);
		mViewPager.initView(getActivity());
就這樣就OK了。


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