ImageSwitcher 사용자 정의

8893 단어
사실android에서 갤러리 보기Gallery와 ImageSwitcher 구성 요소의 사용에 대해 한 글에서 ImageSwitcher의 사용을 소개했습니다. 오늘은 사용자 정의의 ImageSwitcher를 봉합니다. 이것은 제스처 슬라이딩 효과와 애니메이션 효과, 그리고 자동 전환 인터페이스를 제공합니다. 앞으로 이런 수요가 있으면 직접 가져와서 사용할 수 있습니다. 코드는 다음과 같습니다.
MyImageSwitcher:
package com.home.testimageswitcher;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;

public class MyImageSwitcher extends ImageSwitcher {
	private Thread t;//         
	private GestureDetector detector;
	private Context context;
	private int index;//       
	private int[] imageIds;
	public boolean hasStarted = false;//            
	private boolean isSwitching = false;//          
	public boolean isDown = false;//        
	public boolean isFling = false;//       
	private int direction = 1;//   :1     ;-1     
	public Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				setImage(direction);
			}
		}
	};

	public MyImageSwitcher(Context context, int[] imageIds) {
		super(context);
		init(context, imageIds);
	}

	class MyOnGestureListener implements OnGestureListener {

		@Override
		public boolean onDown(MotionEvent e) {
			isDown = true;
			return false;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			isFling = true;
			isSwitching = false;//         
			float instance = e1.getX() - e2.getX();
			if (instance > 10) {
				direction = 1;
				index++;
				if (index > imageIds.length - 1) {
					index = 0;
				}
				setImage(direction);
			} else if (instance < -10) {
				direction = -1;
				index--;
				if (index < 0) {
					index = imageIds.length - 1;
				}
				setImage(direction);
			}
			if (hasStarted) {
				startSwitching();
			}
			return false;
		}

		@Override
		public void onLongPress(MotionEvent e) {
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			return false;
		}

		@Override
		public void onShowPress(MotionEvent e) {
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			return false;
		}

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			if (isDown && !isFling) {
				Toast.makeText(context, "     ", Toast.LENGTH_SHORT).show();
			}
			isDown = false;
			isFling = false;
		}
		return super.onTouchEvent(event);
	}

	/**
	 *    
	 * 
	 * @param context
	 */
	private void init(Context context, int[] imageIds) {
		if (imageIds == null || imageIds.length <= 0) {
			return;
		}
		this.context = context;
		this.imageIds = imageIds;
		if (imageIds.length > 1) {
			this.detector = new GestureDetector(context,
					new MyOnGestureListener());
			this.setOnTouchListener(new MyOnTouchListener());
			this.setLongClickable(true);
		}
		this.setFactory(new MyFactory());
		this.setImageResource(imageIds[index]);
	}

	class MyOnTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			return detector.onTouchEvent(event);
		}
	}

	class MyFactory implements ViewFactory {

		@Override
		public View makeView() {
			ImageView imageView = new ImageView(context);
			imageView.setBackgroundColor(0xFF000000);
			imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			return imageView;
		}
	}

	/**
	 *         
	 */
	public void startSwitching() {
		if (imageIds == null || imageIds.length <= 1) {
			return;
		}
		isSwitching = true;
		if (t == null || !t.isAlive()) {
			t = new Thread() {
				public void run() {
					while (isSwitching) {
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						hasStarted = true;
						if (direction == 1) {
							index++;
						} else {
							index--;
						}
						if (index > imageIds.length - 1) {
							index = 0;
						}
						if (index < 0) {
							index = imageIds.length - 1;
						}
						Message msg = new Message();
						msg.what = 1;
						handler.sendMessage(msg);
					}
				};
			};
			t.start();
		}
	}

	/**
	 *              
	 * 
	 * @param direction
	 */
	private void setImage(int direction) {
		if (direction == 1) {
			setInAnimation(context, R.anim.push_left_in);
			setOutAnimation(context, R.anim.push_left_out);
			setImageResource(imageIds[index]);
		} else {
			setInAnimation(context, R.anim.push_right_in);
			setOutAnimation(context, R.anim.push_right_out);
			setImageResource(imageIds[index]);
		}
	}
}

Activity를 호출하려면 다음과 같이 하십시오.
package com.home.testimageswitcher;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
	private int[] imageIds = { R.drawable.test1, R.drawable.test2,
			R.drawable.test3, R.drawable.test4, R.drawable.test5 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyImageSwitcher switcher = new MyImageSwitcher(this, imageIds);
		setContentView(switcher);
		switcher.startSwitching();//       
	}
}

애니메이션 시리즈:
push_left_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromXDelta="100%p"
        android:toXDelta="0" />

    <alpha
        android:duration="500"
        android:fromAlpha="0.1"
        android:toAlpha="1.0" />

</set>

push_left_out.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromXDelta="0"
        android:toXDelta="-100%p" />

    <alpha
        android:duration="500"
        android:fromAlpha="1.0"
        android:toAlpha="0.1" />

</set>

push_right_in.xml:
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromXDelta="-100%p"
        android:toXDelta="0" />

    <alpha
        android:duration="500"
        android:fromAlpha="0.1"
        android:toAlpha="1.0" />

</set>

push_right_out.xml:
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromXDelta="0"
        android:toXDelta="100%p" />

    <alpha
        android:duration="500"
        android:fromAlpha="1.0"
        android:toAlpha="0.1" />

</set>

좋은 웹페이지 즐겨찾기