利用滑動手勢退出當前Activityjava
windowIsTranslucent = true
Firstly,add the following lines to your app/build.gradle.git
dependencies { compile 'com.aitangba:swipeback:1.0.1' }
Secondly, add the following lines to your application.github
public class CustomApplication extends Application{ @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(ActivityLifecycleHelper.build()); } }
Finally, set the activity which need to swipe extends the SwipeBackActivity.api
public class BaseActivity extends SwipeBackActivity { }
Application在Api14以後添加了新的Callback方法緩存
public void registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks callback) { }
這樣就能夠根據activity的生命週期緩存全部Activity,經過list獲取上一個activity的實例,從而獲取id爲content的ContentView的子View(即setContentView中的View),並進行滑動展現。多線程
默認SwipeBackActivity是支持滑動返回的,不須要滑動返回時則須要複寫SwipeBackActivity的方法supportSlideBack
,其中方法canBeSlideBack
意思是可否返回至本Activity;兩個方法相互配合使用,以應對各類需求。app
public class SwipeBackActivity extends AppCompatActivity implements SwipeBackHelper.SlideBackManager { private static final String TAG = "SwipeBackActivity"; private SwipeBackHelper mSwipeBackHelper; @Override public boolean dispatchTouchEvent(MotionEvent ev) { if(mSwipeBackHelper == null) { mSwipeBackHelper = new SwipeBackHelper(this); } return mSwipeBackHelper.processTouchEvent(ev) || super.dispatchTouchEvent(ev); } @Override public Activity getSlideActivity() { return this; } @Override public boolean supportSlideBack() { return true; } @Override public boolean canBeSlideBack() { return true; } @Override public void finish() { if(mSwipeBackHelper != null) { mSwipeBackHelper.finishSwipeImmediately(); mSwipeBackHelper = null; } super.finish(); } }
private static final int MSG_ACTION_DOWN = 1; //點擊事件 private static final int MSG_ACTION_MOVE = 2; //滑動事件 private static final int MSG_ACTION_UP = 3; //點擊結束 private static final int MSG_SLIDE_CANCEL = 4; //開始滑動,不返回前一個頁面 private static final int MSG_SLIDE_CANCELED = 5; //結束滑動,不返回前一個頁面 private static final int MSG_SLIDE_PROCEED = 6; //開始滑動,返回前一個頁面 private static final int MSG_SLIDE_FINISHED = 7;//結束滑動,返回前一個頁面
Tips:
在設計過程當中遇到也有過其餘思路:
1)設置Activity的透明theme,但是發現只要activity的層級變多就會變得很是卡頓;
2)動態設置Activity的theme,這須要經過反射,並且還須要判斷api,部分手機還不兼容;
3)在滑動展現上個Activity的View時,直接將上個Activity的contentView截圖保存在內存卡上,而後顯示在當前Activity的view上,可是有明顯的卡頓感;
以上都是在設計過程當中想到的方案,也逐個實踐了一下,發現問題仍是比較多的,想一想還不如另闢蹊徑,就有了如今的方案,目前看來仍是能兼容大部分手機的。maven
gitHub地址:https://github.com/XBeats/and_swipebackide