1.宣告
private ViewFlipper flipper02; private ViewFlipper flipper03; private ViewFlipper flipper04; private ImageButton btn_leader_login; //ViewFlipper 集合 private ArrayList<ViewFlipper> flippers; //ViewFlipper 圖片 private int[] resId01 = { R.drawable.area01, R.drawable.area05 }; private int[] resId02 = { R.drawable.area02, R.drawable.area06 }; private int[] resId03 = { R.drawable.area03, R.drawable.area07 }; private int[] resId04 = { R.drawable.area04, R.drawable.area08 };2.初始化
flippers = new ArrayList<>(); flipper01 = (ViewFlipper) findViewById(R.id.vf_area01); flipper02 = (ViewFlipper) findViewById(R.id.vf_area02); flipper03 = (ViewFlipper) findViewById(R.id.vf_area03); flipper04 = (ViewFlipper) findViewById(R.id.vf_area04);3. 使用方法
/** * 自動輪播圖片 */ private void setFilpper() { flippers.add(flipper01); flippers.add(flipper02); flippers.add(flipper03); flippers.add(flipper04); for (int i = 0; i < resId01.length; i++) { flipper01.addView(getImageView(resId01[i])); } for (int i = 0; i < resId02.length; i++) { flipper02.addView(getImageView(resId02[i])); } for (int i = 0; i < resId03.length; i++) { flipper03.addView(getImageView(resId03[i])); } for (int i = 0; i < resId04.length; i++) { flipper04.addView(getImageView(resId04[i])); } Animation inAnimation = new AlphaAnimation(0.5f, 1.0f); inAnimation.setDuration(500); Animation outAnimation = new AlphaAnimation(1.0f, 0.5f); inAnimation.setDuration(500); /** * 每一個ViewFlipper都加上動畫效果 */ for (int i = 0; i < flippers.size(); i++) { flippers.get(i).setInAnimation(inAnimation); flippers.get(i).setOutAnimation(outAnimation); } //隨機輪播一次一張 autoChangeFlipper(); } /** * 每三秒隨機更換一組圖 */ private void autoChangeFlipper() { //目前設置不重複上一次播放的 final ArrayList<ViewFlipper> temp = new ArrayList<>(); for (int i = 0; i < flippers.size(); i++) { temp.add(flippers.get(i)); } //上次選中 final ViewFlipper[] temp1 = new ViewFlipper[1]; handler.postDelayed(new Runnable() { @Override public void run() { if (!repeat) { return; } int count = temp.size(); //本次選中 ViewFlipper vf = temp.get(new Random().nextInt(count)); if (vf != null) { vf.showNext(); //移除本次選中 temp.remove(vf); //不是第一次進來, 把上次選中的加回來 if (count < 4) { temp.add(temp1[0]); } //本次選中的保留,下次要加回來 temp1[0] = vf; handler.postDelayed(this, 3000); //TODO : 目前會離開頁面繼續加入列隊等回來時再一次變更 // if (repeat){ // handler.postDelayed(this,3000); // } } } }, 3000); }WeakRefHandler class
public class WeakRefHandler extends Handler { private WeakReference<Callback> mWeakReference; public WeakRefHandler(Callback callback) { mWeakReference = new WeakReference<Callback>(callback); } public WeakRefHandler(Callback callback, Looper looper) { super(looper); mWeakReference = new WeakReference<Callback>(callback); } @Override public void handleMessage(Message msg) { if (mWeakReference != null && mWeakReference.get() != null) { Callback callback = mWeakReference.get(); callback.handleMessage(msg); } } }
留言
張貼留言