我的应用程序有一个扩展类MarkedLine。这个类的一个实例显示在一个片段中。我希望用户能够做到以下三点:
通过“捏”和“拉伸”手势放大线条
接触线的任何一点,得到它的坐标
把线绕过去
我有前两个在工作,但我想不出第三个(拖拽)。
每个View由一条水平线组成,其中一些是彩色的。用户可以通过拉伸来放大,点击一个框来改变它的颜色;我也希望他们能够在屏幕周围移动行,因为当放大时,它会离开屏幕的边缘。
基本片段布局(MarkedLine)如下(我删除了不相关的位、填充、边距等):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:res="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <packagepath.models.ToolboxButton
        android:id="@+id/toolbarNext"
        android:layout_width="@dimen/toolbar_icon_size"
        android:layout_height="@dimen/toolbar_icon_size"
        android:src="@drawable/next_line"
        res:layout_constraintTop_toTopOf="parent" />

    <packagepath.models.MarkedLine
        android:id="@+id/markedLine"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        res:layout_constraintStart_toStartOf="parent"
        res:layout_constraintEnd_toEndOf="parent"
        res:layout_constraintTop_toBottomOf="@+id/toolbarNext" />

</android.support.constraint.ConstraintLayout>

(所以基本上它是一个按钮,下面有一条全宽的线。该按钮允许用户调出下一行)。
片段代码(fragment_marked_line)如下所示(注意:行集基本上只是一个标记行数组,还有一些额外的变量,如创建时、行维度等):
public class MarkedLineFragment extends Fragment {

    LineSet       mLineSet
    MarkedLine    mMarkedLine;
    ToolboxButton btn_next;

    int     mItemNumber, mMaxItems;

    public MarkedLineFragment() {}

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                     ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(
                R.layout.fragment_marked_line, container, false);

        // Get view objects
        btn_next = rootView.findViewById(R.id.toolbarNext);
        mMarkedLine = rootView.findViewById(R.id.markedLine);

        // Initialise the button
        initialise_button();

        // If the LineSet has already been set,
        //  pass it through to the MarkedLine
        if(mLineSet != null) {
            mMarkedLine.setLineSet(mLineSet);
            mMaxItems = mLineSet.getNum_items();
        }

        // Initialise at line 1
        mItemNumber = 1;
        mMarkedLine.setCurrentItem(mItemNumber);

        // Draw the MarkedLine
        drawLine();

        return rootView;
    }

    // Initialise the button so that it moves to the next line on clicking
    public void initialise_button() {

        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mItemNumber == mMaxItems) return;
                else mItemNumber += 1;
                set_new_item_number();
            }
        });

    }

    private void set_new_item_number() {
        mMarkedLine.setCurrentItem(mItemNumber);
    }

    public void drawChart() {
      if(mMarkedLine != null) mMarkedLine.postInvalidate();
    }

}

最后,MarkedLineFragment类(我省略了如何绘制线的细节,因为我认为它不相关,而且很长-但如果需要,我可以添加它):
public class MarkedLine extends View {

    private LineSet mLineSet;
    private int currentItem;
    private int numBoxes;
    private float canvas_height, canvas_width;
    private float box_size;
    private float minX, maxX, minY, maxY;

    // Scaling (pinch & zoom) variables
    private float scaleFactor = 1.0f; // Current scale factor
    private ScaleGestureDetector detectorScale;// Detector for gestures
    private GestureDetector detectorTouch; // Detector for tap gestures

    public MarkedLine(Context thisContext, AttributeSet attrs) {
        super(thisContext, attrs);

        detectorScale = new ScaleGestureDetector(thisContext, new MarkedLine.ScaleListener());
        detectorTouch = new GestureDetector(thisContext, new MarkedLine.TouchListener());

    }

    public void setCallback(OnBoxTouched callback) { mCallback = callback; }

    public void setLineSet(LineSet lineSet) {
        mLineSet = lineSet;
        numBoxes = mLineSet.getNum_boxes();
        invalidate();
    }

    public void setCurrentItem(int newItemNumber) {
        currentItem = newItemNumber;
        invalidate();
    }

    protected void onDraw(Canvas canvas) {

        if (mLineSet == null) return;

        // Set up canvas
        canvas.save();
        canvas.scale(scaleFactor, scaleFactor);
        canvas.translate(translateX / scaleFactor, translateY / scaleFactor);

        // draw_boxes reads how many boxes make up the MarkedLine,
        //  calculates what size they need to be to fit on the canvas,
        //  and then draws them
        draw_boxes();

        // fill_in_line adds in the appropriate colours to the
        //  boxes in the line
        fill_in_line();

        canvas.restore();
    }

    // GRID EVENT FUNCTIONS - respond to User touching screen

    // onTouchEvent
    // User has touched the screen - trigger listeners
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        detectorScale.onTouchEvent(event);
        detectorTouch.onTouchEvent(event);
        invalidate();

        return true;

    }

    // LISTENERS

    /*
     * Respond to user touching the screen
     */
    private class TouchListener extends GestureDetector.SimpleOnGestureListener {

        public boolean onSingleTapUp(MotionEvent event) {

            // Determine where the screen was touched
            float xTouch = event.getX();
            float yTouch = event.getY();

            // Check that the touch was within the line; return if not
            if(!touch_in_line(xTouch, yTouch)) return false;

            // Figure out which Box was tapped
            int xCell = getTouchedBox(xTouch);

            // Now the box which was tapped is coloured in
            colour_box(xCell);

            return true;
        }

    }

    /*
     * Determine scale factor for zoom mode
     * This can be called in View and Edit Activities
     */
    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {

            float MIN_ZOOM = 1f;     // Minimum zoom level
            float MAX_ZOOM = 5f;     // Maximum zoom level

            scaleFactor *= detector.getScaleFactor();
            scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
            return true;
        }

    }
}

一切正常。用户可以拉伸线条使盒子变大/变小,然后轻触线条上的任何一个方框以使其着色。但是,当用户在屏幕上拖动手指时,我无法让框在屏幕上移动。
我想我需要添加一个ondraglister到某个东西中,但我不知道是什么。我试着用一个ondrag方法创建一个draglistener类,类似于scaleListener和touchListener类(我只有两个伪行,这样我就可以附加一个断点)。然后我声明了该类的一个实例(draglistener)。我尝试使用MarkedLine将它附加到markedline构造函数中,但它没有响应拖动。
然后我在片段中尝试了类似的操作,将其附加到oncreateview中的mmarkedline类中,但再次尝试拖动时它没有响应。
我读过android文档,它建议使用ondraglister类,但我显然做错了什么。

最佳答案

如果它对其他人有帮助,我通过在onTouchEvent类的MarkedLine中添加一个拖拽检查来解决这个问题:

@Override
public boolean onTouchEvent(MotionEvent event) {

    detectorScale.onTouchEvent(event);
    detectorTouch.onTouchEvent(event);

    // Check for drag gestures
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            startX = event.getX() - previousTranslateX;
            startY = event.getY() - previousTranslateY;
            break;
        case MotionEvent.ACTION_UP:
            previousTranslateX = translateX;
            previousTranslateY = translateY;
            break;
        case MotionEvent.ACTION_MOVE:
            translateX = event.getX() - startX;
            translateY = event.getY() - startY;
            break;
    }

    invalidate();

    return true;

}

09-05 05:43