為了讓兩個activity能夠順利切換,花了一些時間研究,
當然中間也遇到一些問題,在這邊紀錄一下.
首先切換Activity是使用intent->startActivity()來做切換
觸發則是長按畫面任意地方
首先先看如何監聽手勢(gesture):
OnGestureListener listener = new OnGestureListener(){
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, switch_target.class);
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
MainActivity.this.finish();
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}};
別忘記要import 所需要的東西
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
動畫的部分,首先要在res/anim裡面新增兩個xml檔
第一個檔,檔名隨意設定
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:interpolator="@android:anim/linear_interpolator"
android:fromXScale="0.0"
android:toXScale="1.0"
android:fromYScale="0.7"
android:toYScale="1.0"
android:fillAfter="false"
android:startOffset="200"
android:duration="200" />
<translate
android:fromXDelta="50%"
android:toXDelta="0"
android:startOffset="200"
android:duration="200"/>
</set>
第二個檔也是檔名隨意設定
有了動畫xml檔 + 手勢(觸發事件),我們還缺一樣東西,就是切換activity
Intent intent = new Intent();
intent.setClass(MainActivity.this, switch_target.class);
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
MainActivity.this.finish();
切換Activity需要的就是intent,注意這邊
intent.setClass(MainActivity.this, switch_target.class);
是MainActivity.this, switch_target.class兩者是不一樣的,請不要搞錯了(搞錯他就會一直報錯)
The method setClass(Context, Class<?>) in the type Intent is not applicable for the arguments...............
這樣的錯誤訊息
另一端切換回來則是:
Intent intent = new Intent();
intent.setClass(switch_target.this,MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
switch_target.this.finish();
當然為了避免還是有人看了以後還是出錯,這邊也附上source code 方便大家看
這次的教學就到此囉 End