我想寻求帮助。
你能给我一个如何通过移动手指来改变活动的建议吗。(如图所示)
谢谢你的回答
图像:https://imageshack.us/download/661/xaxrzF.png
最佳答案
您可以使用gesturedector来完成此任务,下面是工作代码,用您自己的活动替换左、右活动
public class MainActivity extends Activity {
private GestureDetector gesture;
@Override
public void onCreate(Bundle savedInstanceState)
{
gesture = new GestureDetector(new SwipeGestureDetector());
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if (gesture.onTouchEvent(event))
{
return true;
}
return super.onTouchEvent(event);
}
private void onLeft()
{
Intent myIntent = new Intent(MainActivity.this, LeftActivity.class);
startActivity(myIntent);
}
private void onRight()
{
Intent myIntent = new Intent(MainActivity.this, RightActivity.class);
startActivity(myIntent);
}
// Private class for gestures
private class SwipeGestureDetector extends SimpleOnGestureListener
{
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 200;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,float velocityX, float velocityY)
{
try
{
float diffAbs = Math.abs(e1.getY() - e2.getY());
float diff = e1.getX() - e2.getX();
if (diffAbs > SWIPE_MAX_OFF_PATH)
return false;
// Left swipe
if (diff > SWIPE_MIN_DISTANCE&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
MainActivity.this.onLeft();
}
// Right swipe
else if (-diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
MainActivity.this.onRight();
}
}
catch (Exception e)
{
Log.e("MainActivity", "Error on gestures");
}
return false;
}
}
}