1.将图片素材导入到drawable包中
2.编辑activity_main.xml布局资源文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="imgSwitch"
android:text="切换图片"/>
<ZoomControls
android:id="@+id/zoomControls"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/imgControls"
android:layout_width="300dp"
android:layout_height="300dp"
android:paddingTop="20dp"
android:src="@drawable/img1"/>
</LinearLayout>
3.编写MainActivity
(1)声明变量
(2)获取实例
放大:
(4)按钮切换图片
(5)通过手势切换图片
/**
* 手势切换图片
*/
imgIds = new int[IMG_COUNT];
for (int i = 0;i < IMG_COUNT;i++) {
imgIds[i] = getResources().getIdentifier(
"img" + (i + 1),
"drawable",
"net.zxj.hwork18"
);
}
detector = new GestureDetector(new GestureDetector.OnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
Log.i(TAG,"onDown");
return false;
}
@Override
public void onShowPress(MotionEvent e) {
Log.i(TAG,"onShowPress");
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
Log.i(TAG,"onSingleTapUp");
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.i(TAG,"onScroll");
return false;
}
@Override
public void onLongPress(MotionEvent e) {
Log.i(TAG,"onLongPress");
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.i(TAG,"onFling");
if (e2.getX() < e1.getX() - 10) {
if (imgIndex < IMG_COUNT -1 ) {
imgIndex++;
} else {
imgIndex = 0;
}
}
if (e2.getX() > e1.getX() + 10) {
if (imgIndex > 0) {
imgIndex--;
} else {
imgIndex = IMG_COUNT - 1;
}
}
imgControls.setImageResource(imgIds[imgIndex]);
return false;
}
});
将触摸事件交给手势侦测器来处理
完成后运行