之前學習到ViewFlipper實現一個Activity多個控件之間的滑動切換,現在來學習多個activity之間的滑動切換。
1.繼承OnTouchListner和OnGestureListener.
public class WeatherActivity extends Activity implements OnTouchListener,OnGestureListener{
// 2.創建GesTureDetector對象(創建時必須實現OnGestureListnener監聽器實
//例) GestureDetector gd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gd = new GestureDetector((OnGestureListener)this);
// 3.爲當前Acitivity的佈局頁面添加setOnTouchListener事件。(OnCreate函數)
LinearLayout ll = (LinearLayout) findViewById(R.id.weather_layout);
ll.setOnTouchListener(this);
ll.setLongClickable(true);
//注意:若不加setLongClickable(true)的話OnFling會失效,如果不寫這句的話OnGestureListener的重寫方法OnDown方法返回true也可以。只有這樣,view才///能夠處理不同於Tap(輕觸)的hold(即ACTION_MOVE,或者多個ACTION_DOWN),我們同樣可以通過layout定義中的android:longClickable來做到這一點。 //4.將Acityvity的TouchEvent事件交給GestureDetector處理@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return gd.onTouchEvent(event);
}
// 5.重載onFling函數
@Override
//e1 The first down motion event that started the fling.手勢起點的移動事件
//e2 The move motion event that triggered the current onFling.當前手勢點的移動事件
//velocityX The velocity of this fling measured in pixels per second along the x axis.每秒x軸方向移動的像素
//velocityY The velocity of this fling measured in pixels per second along the y axis.每秒y軸方向移動的像素
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
if(e1.getX() - e2.getX() > FLING_MIN_DISTANCE&&Math.abs(velocityX) > FLING_MIN_VELOCITY)
{
Intent intent = new Intent(WeatherActivity.this,CityActivity.class);
startActivity(intent);
Toast.makeText(this, "向左手勢", Toast.LENGTH_SHORT).show();
}
else if (e2.getX()-e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) >FLING_MIN_VELOCITY) {
//切換Activity
Intent intent = new Intent(WeatherActivity.this, IndexActivity.class);
startActivity(intent);
Toast.makeText(this, "向右手勢", Toast.LENGTH_SHORT).show();
}
return false;
}