效果如下:
布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/img1"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
主界面代码:
package com.example.beautyphtotos;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener{
/**
* 手势侦测器
*/
private GestureDetector detector;
/**
* 图像标识数组
*/
private int[]imgIds;
/**
* 图像索引,表示在数组中的位置
*/
private int imgIndex;
/**
* 图片数量
*/
private static final int IMG_COUNT=23;
/**
* 根布局
*/
private LinearLayout linearLayout;
/**
* 应用程序标记
*/
private final String TAG="swith_belle_image";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过资源标识
linearLayout=findViewById(R.id.root);
//初始化图像标识数组
imgIds=new int[IMG_COUNT];
for (int i=0;i<IMG_COUNT;i++){
imgIds[i]=getResources().getIdentifier("img"+(i+1),"mipmap","com.example.beautyphtotos");
}
//实例化手势侦测器(参数1:上下文环境,参数2:手势监听器对象)
detector=new GestureDetector(this,this);
}
/**
* 将窗口触摸事件交给手势侦测器处理
*
*/
public boolean onTouchEvent(MotionEvent event){
return detector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e) {
Toast.makeText(MainActivity.this,"温馨提示:左右滑动可切换图片",Toast.LENGTH_SHORT).show();
Log.d(TAG, "onDown");
return true;
}
@Override
public void onShowPress(MotionEvent e) {
Log.d(TAG, "onShowPress");
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d(TAG, "onSingleTapUp");
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.d(TAG, "onDown");
return true;
}
@Override
public void onLongPress(MotionEvent e) {
Log.d(TAG, "onLongPress");
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.d(TAG, "onFling");
//手势往左滑动10个像素,图片切换到下一张
if (e1.getX()-e2.getX()>=10){
//更改图像索引
if (imgIndex<IMG_COUNT-1){
imgIndex++;
}else {
imgIndex=0;
}
}
//手势向右滑动10个像素,图片切换上一张
if (e2.getX()-e1.getX()>=10){
//更新图像索引
if (imgIndex>0){
imgIndex--;
}else {
imgIndex=IMG_COUNT-1;
}
}
//利用更改后的图像索引去设置根布局的背景图片
linearLayout.setBackgroundResource(imgIds[imgIndex]);
//返回真事件处理到此完毕
return true;
}
}