本文實例為大家分享了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; } };}
界面設置效果:
這個功能的代碼里有很多沒見過的單詞,本人英語學的不好,需要查查意思然后找這些方法的功能。
可以用這個加上切換動畫做一個圖片查看器。
由于沒用模擬器,用的是真機調試,給不了滑動的實物圖,抱歉抱歉。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答