一、新建ImageViewer模块,添加p1-p9图片(注意mdpi后缀)
二、相关代码
1.MainActivity.java文件代码
package com.example.imageviewer;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
public class MainActivity extends AppCompatActivity {
private int[] arrayPicture = new int[]{R.drawable.p1,R.drawable.p2,R.drawable.p3,R.drawable.p4,
R.drawable.p5,R.drawable.p6,R.drawable.p7,R.drawable.p8,R.drawable.p9};
private ImageSwitcher imageSwitcher;
private int index;
private float touchDownX;
private float touchUpX;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //设置全屏显示
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitcher);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(arrayPicture[index]);
return imageView;
}
});
imageSwitcher.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
touchDownX = event.getX();
return true;
}else if(event.getAction() == MotionEvent.ACTION_UP){
touchUpX = event.getX();
if(touchUpX-touchDownX>100){
index = index == 0?arrayPicture.length-1:index-1;
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_out_right));
imageSwitcher.setImageResource(arrayPicture[index]);
}else if (touchDownX-touchUpX>100){
index = index == arrayPicture.length-1?0:index+1;
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_right));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_out_left));
imageSwitcher.setImageResource(arrayPicture[index]);
}
return true;
}
return false;
}
});
}
}
2.activity_main.xml文件代码
<?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">
<ImageSwitcher
android:id="@+id/imageswitcher"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageSwitcher>
</RelativeLayout>
三、运行结果(图像可以左右拖动)