I haven’t written a blog for a long time. I have been busy with the project recently. I’d like to write a blog while I have a lunch break.
- The effect
- Inherit the appropriate View.
public class VerticalTouchImageView extends android.support.v7.widget.AppCompatImageView{
}
Copy the code
- Constructor For convenience, if the constructor calls other constructors through this, we can place the initialization logic in the last constructor called.
public VerticalTouchImageView(Context context) { this(context, null); } public VerticalTouchImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VerticalTouchImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //TODO does the initialization}Copy the code
- Override the onTouchEvent method, which needs to handle the event because of the gesture.
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return super.onTouchEvent(event);
}
Copy the code
Complete code (code analysis) :
/** * Home drag control, can only drag vertically. * Created by Chao on 2017-11-16. */ public class VerticalTouchImageView extends android.support.v7.widget.AppCompatImageView { public VerticalTouchImageView(Context context) { this(context, null); } public VerticalTouchImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VerticalTouchImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }floatmoveY; /** * Since project requirements can only slide up and down, we only care about the Y-axis. */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) {caseMotionevent.action_down: // Record the current pressed Y coordinate moveY = event.getrawy ();break;
caseACTION_MOVE: // In the Move event, take the current Y coordinate minus the coordinate at the time of press to calculate how far the View should Move.float y = event.getRawY();
floatdiffY = y - moveY; // If the current Y coordinate has been moved off-screen, we need to modify the coordinate, at most to the top 0 coordinate.if (getY() <= 0) {
setY(0);
} else{// If it does not exceed the boundary, we move the View.setY(currY); } // return heretrueConsume this incident and deal with it yourself.return true;
case MotionEvent.ACTION_UP:
break;
}
returnsuper.onTouchEvent(event); } /** * reset method */ public voidreset() {
if (getY() <= 0) {
setY(0); }}}Copy the code