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;
        }
    };
}

界面设置效果:



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

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

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


评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值