您的位置:首页 > 移动开发 > Android开发

Android实现滑动屏幕切换图片

2018-08-29 16:17 776 查看

本文实例为大家分享了Android实现滑动屏幕切换图片的具体代码,供大家参考,具体内容如下

activity_main.xml 文件代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.example.administrator.hand_gliding.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView"
android:src="@drawable/a1"/>
</LinearLayout>

MainActivity.java 文件代码:

package com.example.administrator.hand_gliding;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
//定义图片
private int[] resId = new int[]{
R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,
R.drawable.a5,R.drawable.a6,R.drawable.a7
};
//图片下标序号
private int count = 0;
//定义手势监听对象
private GestureDetector gestureDetector;
//定义ImageView对象
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView)findViewById(R.id.imageView);        //获取ImageView控件id
gestureDetector = new GestureDetector(onGestureListener);  //设置手势监听由onGestureListener处理
}
//当Activity被触摸时回调
public boolean onTouchEvent(MotionEvent event){
return gestureDetector.onTouchEvent(event);
}
//自定义GestureDetector的手势识别监听器
private GestureDetector.OnGestureListener onGestureListener
= new GestureDetector.SimpleOnGestureListener(){
//当识别的手势是滑动手势时回调onFinger方法
public boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY){
//得到手触碰位置的起始点和结束点坐标 x , y ,并进行计算
float x = e2.getX()-e1.getX();
float y = e2.getY()-e1.getY();
//通过计算判断是向左还是向右滑动
if(x > 0){
count++;
count%=(resId.length-1);    //想显示多少图片,就把定义图片的数组长度-1
}else if(x < 0){
count--;
count=(count+(resId.length-1))%(resId.length-1);
}
iv.setImageResource(resId[count]); //切换imageView的图片
return true;
}
};
}

界面设置效果:

这个功能的代码里有很多没见过的单词,本人英语学的不好,需要查查意思然后找这些方法的功能。

可以用这个加上切换动画做一个图片查看器。

由于没用模拟器,用的是真机调试,给不了滑动的实物图,抱歉抱歉。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息