Created
January 20, 2018 17:34
-
-
Save dbof10/7aa39831a4015647cbaee407801fd224 to your computer and use it in GitHub Desktop.
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
import android.content.Context; | |
import android.os.Build; | |
import android.support.annotation.RequiresApi; | |
import android.support.v7.widget.AppCompatImageView; | |
import android.util.AttributeSet; | |
import android.view.MotionEvent; | |
import android.view.View; | |
import static android.view.MotionEvent.ACTION_DOWN; | |
import static android.view.MotionEvent.ACTION_MOVE; | |
import static android.view.MotionEvent.ACTION_UP; | |
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) | |
public class AlphaImageView extends AppCompatImageView { | |
private float rawX; | |
private int alpha; | |
private AlphaChangeListener listener; | |
public AlphaImageView(Context context) { | |
super(context); | |
this.rawX = -1.0f; | |
this.alpha = -1; | |
} | |
public AlphaImageView(Context context, AttributeSet attributeSet) { | |
super(context, attributeSet); | |
this.rawX = -1.0f; | |
this.alpha = -1; | |
} | |
public AlphaImageView(Context context, AttributeSet attributeSet, int i) { | |
super(context, attributeSet, i); | |
this.rawX = -1.0f; | |
this.alpha = -1; | |
} | |
public void setAlphaListener(AlphaChangeListener listener) { | |
this.listener = listener; | |
} | |
public void reset() { | |
setImageAlpha(255); | |
} | |
@Override | |
public boolean onTouchEvent(MotionEvent motionEvent) { | |
switch (motionEvent.getAction()) { | |
case ACTION_DOWN: | |
rawX = motionEvent.getRawX(); | |
alpha = getImageAlpha(); | |
if (listener != null) { | |
float alpha = (float) (((double) getImageAlpha()) / 255.0d); | |
listener.onStart(alpha); | |
break; | |
} | |
break; | |
case ACTION_UP: | |
rawX = -1.0f; | |
alpha = -1; | |
if (listener != null) { | |
listener.onStop(); | |
break; | |
} | |
break; | |
case ACTION_MOVE: | |
if (getVisibility() == View.VISIBLE && getDrawable() != null && | |
motionEvent.getActionIndex() == ACTION_DOWN && rawX >= 0.0f) { | |
int min = Math.min(alpha - | |
((int) ((((double) (rawX - motionEvent.getRawX())) / (((double) getMeasuredWidth()) * 0.6d)) * 255.0d)), 255); | |
int max = Math.max(0, min); | |
setImageAlpha(max); | |
if (listener != null) { | |
float alpha = (float) (((double) max) / 255.0d); | |
listener.onChange(alpha); | |
break; | |
} | |
} | |
break; | |
} | |
return true; | |
} | |
public interface AlphaChangeListener { | |
void onStop(); | |
void onStart(float alpha); | |
void onChange(float alpha); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment