Created
November 18, 2014 00:24
-
-
Save matiash/d772bbb1ca4c0803db65 to your computer and use it in GitHub Desktop.
ActivityDragImage.java - Drag image horizontally and scale it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.androidtests; | |
import android.annotation.SuppressLint; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.view.Display; | |
import android.view.MotionEvent; | |
import android.view.View; | |
import android.widget.ImageView; | |
import android.widget.RelativeLayout; | |
import com.nineoldandroids.view.ViewPropertyAnimator; | |
public class ActivityDragImage extends Activity | |
{ | |
private ImageView mImage; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) | |
{ | |
super.onCreate(savedInstanceState); | |
RelativeLayout mainLayout = new RelativeLayout(this); | |
setContentView(mainLayout); | |
mImage = new ImageView(this); | |
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); | |
lp.addRule(RelativeLayout.CENTER_IN_PARENT); | |
mainLayout.addView(mImage, lp); | |
mImage.setImageResource(R.drawable.square400px); | |
mImage.setOnTouchListener(mTouchListener); | |
} | |
private View.OnTouchListener mTouchListener = new View.OnTouchListener() | |
{ | |
private float mStartX; | |
@Override | |
public boolean onTouch(View v, MotionEvent event) | |
{ | |
switch (event.getActionMasked()) | |
{ | |
case MotionEvent.ACTION_DOWN : | |
mStartX = event.getRawX(); | |
return true; | |
case MotionEvent.ACTION_MOVE : | |
float currentX = event.getRawX(); | |
animateTo(currentX - mStartX, true); // Snap to drag | |
return true; | |
case MotionEvent.ACTION_UP : | |
case MotionEvent.ACTION_CANCEL : | |
animateTo(0, false); // Ease back | |
return true; | |
} | |
return false; | |
} | |
}; | |
private void animateTo(float displacement, boolean immediate) | |
{ | |
final int EASE_BACK_DURATION = 300; // ms | |
int duration = (immediate ? 0 : EASE_BACK_DURATION); | |
Display display = getWindowManager().getDefaultDisplay(); | |
int totalWidth = display.getWidth(); | |
float scale = 1.0f - Math.abs(displacement / totalWidth); | |
ViewPropertyAnimator.animate(mImage) | |
.translationX(displacement) | |
.scaleX(scale) | |
.scaleY(scale) | |
.setDuration(duration) | |
.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment