Android开发之手势之一个切换图片的demo
今天我们来学习一个用ViewFlipper加手势检测做的demo,
Java代码如下:
package com.zking.administrator.g160628_android20_gesture;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class MainActivity extends AppCompatActivity {
private ViewFlipper vf_main_image;
private int images[]={R.drawable.s1,R.drawable.s2,R.drawable.s3};
private GestureDetector gd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vf_main_image = (ViewFlipper) findViewById(R.id.vf_main_image);
for (int i = 0; i < images.length; i++) {
ImageView iv=new ImageView(this);
iv.setImageResource(images[i]);
vf_main_image.addView(iv);
}
//实例化手势检测器类
gd = new GestureDetector(this, new GestureDetector.OnGestureListener() {
//按下
@Override
public boolean onDown(MotionEvent e) {
Log.i("test","onDown");
return false;
}
//按下,但是还未抬起
@Override
public void onShowPress(MotionEvent e) {
Log.i("test","onShowPress");
}
//轻按,按一下,立刻抬起
@Override
public boolean onSingleTapUp(MotionEvent e) {
Log.i("test","onSingleTapUp");
return false;
}
//滚动
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.i("test","onScroll");
return false;
}
//长按
@Override
public void onLongPress(MotionEvent e) {
Log.i("test","onLongPress");
}
//拖动
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.i("test","onFling");
if(e2.getX()-e1.getX()>200){
Toast.makeText(MainActivity.this, "右滑,上一张", Toast.LENGTH_SHORT).show();
vf_main_image.showPrevious();
//左进右出
vf_main_image.setInAnimation(MainActivity.this,R.anim.left_in);
vf_main_image.setOutAnimation(MainActivity.this,R.anim.right_out);
}
if(e1.getX()-e2.getX()>200){
Toast.makeText(MainActivity.this, "左滑,下一张", Toast.LENGTH_SHORT).show();
vf_main_image.showNext();
//左出右进
vf_main_image.setInAnimation(MainActivity.this,R.anim.right_in);
vf_main_image.setOutAnimation(MainActivity.this,R.anim.left_out);
}
return false;
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Log.i("test","onTouchEvent");
return gd.onTouchEvent(event);
}
}
xml没有什么代码,主要给这个设置了几个动画,这个也是可以自己设计的,代码也是能懂得,就这样byebye!!!!!!!!