Android 画直线并实现拖动

自定义View,在onDraw()方法中绘制一条直线,在onTouch()方法中监听手指的移动。

public class AroundDragView extends View implements View.OnTouchListener {
    private static final String TAG = "ImageLight";
    protected int screenWidth;
    protected int screenHeight;
    protected int lastX;
 
    protected Paint paint = new Paint();
    int offset = 30;public AroundDragView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setOnTouchListener(this);
    }

    public AroundDragView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnTouchListener(this);
    }

    public AroundDragView(Context context) {
        super(context);
        setOnTouchListener(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.YELLOW);
        paint.setStrokeWidth(4.0f);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawLine(offset / 2, 0, offset / 2, getHeight(), paint);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                oriLeft = v.getLeft();
                oriRight = v.getRight();
                lastX = (int) event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - lastX;
                move(v, dx);
                lastX = (int) event.getRawX();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        invalidate();
        return false;
    }

    /**
     * 移动
     *
     * @param v
     * @param dx
     */
    private void move(View v, int dx) {
        int left = v.getLeft() + dx;
        int right = v.getRight() + dx;
        if (left < 100 + offset) {
            left = 100 + offset;
            right = left + v.getWidth();
        }
        if (right > screenWidth - 100) {
            right = screenWidth - 100;
            left = right - v.getWidth();
        }
        v.layout(left, 0, right, getHeight());
    }

}

将上面的View作为一个View放在XML文件中即可,例如:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center">

    <com.desmand.utils.AroundDragView
        android:id="@+id/video_around_drag_view"
        android:layout_width="20dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:clickable="true"/>
</RelativeLayout>

 

参考:http://www.cnblogs.com/a284628487/p/3367228.html

 

posted @ 2015-12-18 09:06  渐行渐远渐无声  阅读(745)  评论(0编辑  收藏  举报