package com.myluffy.util.im2;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
/**
* 下拉放大指定{@link PullToZoomInLayout#mZoomInView} View
*/
public class PullToZoomInLayout extends ScrollView {
private int mDownY;
// 被放大view原始的高
private int mZoomInViewInitialHeight;
// 被放大的view
private View mZoomInView;
// 被放大view的ID
private final int mZoomInID;
// 被放大view的布局参数
private ViewGroup.LayoutParams mZoomInViewLP;
public PullToZoomInLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray t = getContext().obtainStyledAttributes(attrs, R.styleable.Pull);
mZoomInID = t.getResourceId(R.styleable.Pull_pull_id, -1);
t.recycle();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mZoomInView == null) {
return super.onInterceptTouchEvent(ev);
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownY = (int) ev.getY();
break;
case MotionEvent.ACTION_MOVE:
if (getScrollY() == 0) {
if (ev.getY() - mDownY > 0) {
return true;
}
}
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mZoomInView == null) {
return super.onTouchEvent(ev);
}
// 超出屏幕.
if (ev.getY() >= getHeight()) {
restoreLayout();
return true;
}
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
if (getScrollY() == 0) {
int offset = (int) ((ev.getY() - mDownY) * 0.5);
if (offset > 0) {
mZoomInViewLP.height = mZoomInViewInitialHeight + offset;
mZoomInView.setLayoutParams(mZoomInViewLP);
return true;
}
}
break;
case MotionEvent.ACTION_UP:
restoreLayout();
break;
}
return super.onTouchEvent(ev);
}
private void restoreLayout() {
if (mZoomInViewLP.height > mZoomInViewInitialHeight) {
ValueAnimator anim = ValueAnimator.ofInt(mZoomInViewLP.height, mZoomInViewInitialHeight)
.setDuration(300);
anim.start();
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mZoomInViewLP.height = (int) animation.getAnimatedValue();
mZoomInView.setLayoutParams(mZoomInViewLP);
}
});
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (mZoomInID != -1) {
mZoomInView = findViewById(mZoomInID);
mZoomInView.post(new Runnable() {
@Override
public void run() {
mZoomInViewInitialHeight = mZoomInView.getHeight();
}
});
}
}
@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
if (mZoomInView != null) {
mZoomInViewLP = mZoomInView.getLayoutParams();
}
}
}