2015-08-17 109 views
4

我有2個活動,我想要在它們之間切換滑動,我已經做了大量的谷歌研究,但無法找到解決方案,因爲我正在使用位圖(圖像)的活動的onCreate()方法中編寫代碼,有沒有這方面的任何解決方案,或者我如何轉換的活動就像是進入一個片段滑動之間的活動

+1

爲什麼不使用Fragments和ViewPager? – Gavin

+0

我已經創建了一個活動來顯示SD卡圖像,並從中選擇,所以我可以顯示在其他活動(編輯活動),我可以編輯他們,我不知道我是否可以將活動轉換成片段完全一樣 –

+0

這不是很難轉換,活動中的一點點改變就能完成這項工作!祝你好運 – Gavin

回答

1

可以通過使用GestureDetector來完成。以下是示例代碼片段。

// You can change values of below constants as per need. 
private static final int MIN_DISTANCE = 100; 
private static final int MAX_OFF_PATH = 200; 
private static final int THRESHOLD_VELOCITY = 100; 
private GestureDetector mGestureDetector; 

// write below code in onCreate method 
mGestureDetector = new GestureDetector(context, new SwipeDetector()); 

// Set touch listener to parent view of activity layout 
// Make sure that setContentView is called before setting touch listener. 
findViewById(R.id.parent_view).setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       // Let gesture detector handle the event 
       return mGestureDetector.onTouchEvent(event); 
      } 
     }); 


// Define a class to detect Gesture 
private class SwipeDetector extends GestureDetector.SimpleOnGestureListener { 
     @Override 
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
      if (e1 != null && e2 != null) { 
       float dy = e1.getY() - e2.getY(); 
       float dx = e1.getX() - e2.getX(); 

       // Right to Left swipe 
       if (dx > MIN_DISTANCE && Math.abs(dy) < MAX_OFF_PATH && 
         Math.abs(velocityX) > THRESHOLD_VELOCITY) { 
      // Add code to change activity 
        return true; 
       } 

       // Left to right swipe 
       else if (-dx > MIN_DISTANCE && Math.abs(dy) < MAX_OFF_PATH && 
         Math.abs(velocityX) > THRESHOLD_VELOCITY) { 
      // Below is sample code to show left to right swipe while launching next activity 
      currentActivity.overridePendingTransition(R.anim.right_in, R.anim.right_out); 
      startActivity(new Intent(currentActivity,NextActivity.class)); 
        return true; 
       } 
      } 
      return false; 
     } 
} 

//Below are sample animation xml files. 

anim/right_in.xml 
<?xml version="1.0" encoding="utf-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
    <translate 
     android:duration="500" 
     android:fromXDelta="-100%p" 
     android:toXDelta="0" /> 
</set> 

anim/right_out.xml 
<?xml version="1.0" encoding="utf-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
    <translate 
     android:duration="500" 
     android:fromXDelta="0" 
     android:toXDelta="100%p" /> 
</set> 
+0

它工作正常,謝謝你,但我想要的是看到幻燈片效果和活動已被打開,畢竟這些嘗試後,我正在考慮將每個活動轉換成片段,再次感謝你! –

+0

對於幻燈片效果,您可以使用動畫和活動的overridePendingTransition方法。檢查我更新的答案。但是,我同意使用片段是正確的方法。 –

+0

我已經實現了我想使用片段的結果,再次感謝您的回答! –