切换缩放图片
切换功能
1.导入3张图片到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:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/img1"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
3.编写MainActivity
package net.zxj.hwork14;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private GestureDetector detector; //手势侦测器
private int [] imgIds; //图像资源标识符数组
private int imgIndex; //图像索引,反映在图像资源标识符数组中的位置
private LinearLayout root;//根线性布局
private final static int IMG_COUNT = 3; //图像总数
private final static String TAG = "hwork14"; //定义程序标记
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过资源标识符获取控件实例
root = findViewById(R.id.root);
//初始化图像资源标识符数组
imgIds = new int[IMG_COUNT];
for(int i=0; i< IMG_COUNT;i++){
imgIds[i] = getResources().getIdentifier(
"img" + (i+1), //标识符名称
"drawable", //定义类型
"net.zxj.hwork14" //定义包名
);
}
//设置根布局可以获得焦点
root.setFocusable(true);
//让根布局获取焦点
root.requestFocus();
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");
//手势往左滑动20个像素,图像切换到下一张
if (e2.getX() < e1.getX() -20){
if (imgIndex < IMG_COUNT -1){
imgIndex ++;
}else {
imgIndex = 0;
}
}
//手势往右滑20个像素,图像切换到上一张
if (e2.getX() > e1.getX() +20){
if (imgIndex>0){
imgIndex--;
}else{
imgIndex = IMG_COUNT -1;
}
}
//要根据变化之后图像索引更新布局的背景图片
root.setBackgroundResource(imgIds[imgIndex]);
return false;
}
});
}
//将窗口的触摸事件交给手势侦测器来处理
@Override
public boolean onTouchEvent(MotionEvent event) {
return detector.onTouchEvent(event);
}
}