Android (滑動屏幕切換圖片的實現)

一、首先實現界面部分

代碼:

<?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">

    <ImageView
        android: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.jpg
    private int[] photoIndex = new int[]{
            R.drawable.a1,R.drawable.a2
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取圖片id
        iv = findViewById(R.id.photo);
        //OnGestureListener處理手勢監聽
        gd = new GestureDetector(this,OnGestureListener);
    }

    //當此Activity被觸摸時回調,這裏用到了觸摸回調:onTouchEvent
    //按下回調是:onKeyDown,擡起回調:onKeyUp
     public boolean onTouchEvent(MotionEvent event) {
        gd.onTouchEvent(event);
        //必須是true
        return true;
    }
    /**
     *自定義GestureDetector的手勢識別監聽器
     */
    private GestureDetector.OnGestureListener OnGestureListener = new GestureDetector.SimpleOnGestureListener(){
        //滑屏:用戶按下觸摸屏、快速移動後鬆開.識別是滑屏後回調onFling方法
        @Override
        public 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;
        }
    };
}

三、實現效果

效果還不錯,但看着很僵硬,,,。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章