一、首先实现界面部分
代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/a1"/>
</RelativeLayout>
界面部分只用到了一个ImageView。
二、实现图片的切换
package com.liu.photoslide;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
//定义ImageView对象
private ImageView iv;
//图片的下标
private int count = 0;
//定义手势监听对象
private GestureDetector gd;
//定义图片数组,这里我就用到了两张图片a1.jpg,a2.jpg
private int[] photoIndex = new int[]{
R.drawable.a1,R.drawable.a2
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取图片id
iv = findViewById(R.id.photo);
//OnGestureListener处理手势监听
gd = new GestureDetector(this,OnGestureListener);
}
//当此Activity被触摸时回调,这里用到了触摸回调:onTouchEvent
//按下回调是:onKeyDown,擡起回调:onKeyUp
public boolean onTouchEvent(MotionEvent event) {
gd.onTouchEvent(event);
//必须是true
return true;
}
/**
*自定义GestureDetector的手势识别监听器
*/
private GestureDetector.OnGestureListener OnGestureListener = new GestureDetector.SimpleOnGestureListener(){
//滑屏:用户按下触摸屏、快速移动后松开.识别是滑屏后回调onFling方法
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//获取手指触碰座标,计算是向左滑还是向右滑
float x = e2.getX()-e1.getX();
if(x>0){
count ++;
count = count%(photoIndex.length);
}else if(x<0){
count --;
count = (count+(photoIndex.length))%(photoIndex.length);
}
//切换图片
iv.setImageResource(photoIndex[count]);
return true;
}
};
}
三、实现效果
效果还不错,但看着很僵硬,,,。