2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Android (滑动屏幕切换图片的实现)

Android (滑动屏幕切换图片的实现)

时间:2019-06-22 20:27:54

相关推荐

Android (滑动屏幕切换图片的实现)

一、首先实现界面部分

代码:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><ImageViewandroid:id="@+id/photo"android:layout_width="match_parent"android:layout_height="match_parent"android:src="@drawable/a1"/></RelativeLayout>

界面部分只用到了一个ImageView。

二、实现图片的切换

package com.liu.photoslide;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.GestureDetector;import android.view.MotionEvent;import android.widget.ImageView;public class MainActivity extends AppCompatActivity {//定义ImageView对象private ImageView iv;//图片的下标private int count = 0;//定义手势监听对象private GestureDetector gd;//定义图片数组,这里我就用到了两张图片a1.jpg,a2.jpgprivate int[] photoIndex = new int[]{R.drawable.a1,R.drawable.a2};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//获取图片idiv = findViewById(R.id.photo);//OnGestureListener处理手势监听gd = new GestureDetector(this,OnGestureListener);}//当此Activity被触摸时回调,这里用到了触摸回调:onTouchEvent//按下回调是:onKeyDown,抬起回调:onKeyUppublic boolean onTouchEvent(MotionEvent event) {gd.onTouchEvent(event);//必须是truereturn true;}/***自定义GestureDetector的手势识别监听器*/private GestureDetector.OnGestureListener OnGestureListener = new GestureDetector.SimpleOnGestureListener(){//滑屏:用户按下触摸屏、快速移动后松开.识别是滑屏后回调onFling方法@Overridepublic boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {//获取手指触碰坐标,计算是向左滑还是向右滑float x = e2.getX()-e1.getX();if(x>0){count ++;count = count%(photoIndex.length);}else if(x<0){count --;count = (count+(photoIndex.length))%(photoIndex.length);}//切换图片iv.setImageResource(photoIndex[count]);return true;}};}

三、实现效果

效果还不错,但看着很僵硬,,,。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。