软件编程
位置:首页>> 软件编程>> Android编程>> Android实现滑动屏幕切换图片

Android实现滑动屏幕切换图片

作者:Code_MoMo  发布时间:2022-04-26 23:14:42 

标签:Android,滑动,切换图片

本文实例为大家分享了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;
}
};
}

界面设置效果:

Android实现滑动屏幕切换图片

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

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

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

来源:https://blog.csdn.net/Code_MoMo/article/details/78760862

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com