自定义一个ImageSwitcher

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

其实,在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>







 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
大图查看,它能够动画顺畅切换到查看状态,同样动画顺畅退出查看界面左右滑动多图查看仿微信下拽退出   示例下载在 previews文件夹下 app-debug.apk app-debug.apk对比之前1.0.3,修复-宽高计算错误导致起始图片位置显示错误。优化-取消了无意义的旋转,提示下拽体验(放大且图片已显示顶端时亦可下拽)。优化-支持显示本地图片。新增-支持长图显示(beta)。 使用的网络图片,被屏蔽了请自己换地址,或提醒我。新增-自定义loadingUI新增-自定义indexUI集成Add it in your root build.gradle at the end of repositories:allprojects {     repositories {         ...         maven { url 'https://jitpack.io' }     } }Add the dependencydependencies {     implementation 'com.github.iielse:ImageWatcher:1.1.0' }初始化API简介namedescription*setLoader*图片地址加载的实现者setTranslucentStatus当没有使用透明状态栏,传入状态栏的高度setErrorImageRes图片加载失败时显示的样子setOnPictureLongPressListener长按回调setIndexProvider自定义页码UIsetLoadingUIProvider自定义加载UIsetOnStateChangedListener开始显示和退出显示时的回调初始化配置Activity.onCreate()vImageWatcher = ImageWatcherHelper.with(this) // 一般来讲,ImageWatcher尺寸占据全屏     .setLoader(new GlideImageWatcherLoader()) // demo中有简单实现     .setIndexProvider(new DotIndexProvider()) // 自定义     .create();Activity.onBackPressed()if (!vImageWatcher.handleBackPressed()) {     super.onBackPressed(); }使用ImageView clickedImage = 被点击的ImageView; SparseArray<ImageView> mapping = new SparseArray<>(); // 这个请自行理解, mapping.put(0, clickedImage); List<Uri> dataList = 被显示的图片们; vImageWatcher.show(clickedImage, mapping, dataList);具体看源码demo示例。项目可运行。欢迎提出问题/想法。楼主也许可能会更新,比如这次 /斜眼笑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u010142437

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值