Android 推门效果
2015-10-17 23:00 Weiggle 阅读(254) 评论(0) 编辑 收藏 举报public class MainActivity extends RelativeLayout{ private Scroller scroller; private Context context; private int width; private int height; private ImageView imageView; private int mLastDownY = 0; private int mCurryY; private int mDelY; private boolean mCloseFlag = false; public Main_skip(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; initView(); } private void initView(){ // 这个Interpolator你可以设置别的 我这里选择的是有弹跳效果的Interpolator BounceInterpolator interpolator = new BounceInterpolator(); scroller = new Scroller(context,interpolator); WindowManager manager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(metrics); width = metrics.widthPixels; height = metrics.heightPixels; // 这里你一定要设置成透明背景,不然会影响你看到底层布局 this.setBackgroundColor(Color.argb(0, 0, 0, 0)); imageView = new ImageView(context); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT , LayoutParams.MATCH_PARENT); imageView.setLayoutParams(params); imageView.setScaleType(ScaleType.FIT_XY); imageView.setImageResource(R.drawable.a); addView(imageView); } public void setBGimg(int resID){ imageView.setImageResource(resID); } public void setBGimg(Drawable drawable){ imageView.setImageDrawable(drawable); } // 推动门的动画 public void setAnimation(int startY, int dy, int duration){ scroller.startScroll(0, startY, 0, dy, duration); invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mLastDownY = (int) event.getY(); System.err.println("ACTION_DOWN=" + mLastDownY); return true; case MotionEvent.ACTION_MOVE: mCurryY = (int) event.getY(); System.err.println("ACTION_MOVE=" + mCurryY); mDelY = mCurryY - mLastDownY; if(mDelY < 0 ){ scrollTo(0, -mDelY); System.err.println("------------- " + mDelY); } break; case MotionEvent.ACTION_UP: mCurryY = (int) event.getY(); mDelY = mCurryY - mLastDownY; if(mDelY < 0){ if(Math.abs(mDelY)>height/2){ setAnimation(this.getScrollY(), height, 450); mCloseFlag = true; }else{ setAnimation(this.getScrollY(), -this.getScrollY(), 1000); } } break; default: break; } return super.onTouchEvent(event); } @Override public void computeScroll() { if(scroller.computeScrollOffset()){ scrollTo(scroller.getCurrX(), scroller.getCurrY()); // 不要忘记更新界面 postInvalidate(); }else { if (mCloseFlag) { this.setVisibility(View.GONE); } } super.computeScroll(); } }