同步滚动多个自定义视图

时间:2016-11-08 11:22:06

标签: android ontouchlistener custom-view

我有自定义视图,它绘制比例并处理触摸事件(该比例的横向滚动)。绘图部分:

@Override
public void onDraw(Canvas canvas){
    startingPoint = mainPoint;
    counter = 0;
    int i = 0;

    while (startingPoint <= scaleWidth) {
        if(i % 4 == 0) {
            size = scaleHeight / 4;

            if (counter < 24) {
                counter = counter + 1;
            } else {
                counter = 1;
            }

            String c = Integer.toString(counter);
            canvas.drawText(c, startingPoint, endPoint - (size + 20), textPaint);

        } else {
            if(i % 2 == 0) {
                size = scaleHeight / 8;
            } else {
                size = scaleHeight / 16;
            }
        }

        if(startingPoint >= closest) {
            //метки шкалы
            canvas.drawLine(startingPoint, endPoint - size, startingPoint, endPoint, rulerPaint);

        }

        startingPoint = startingPoint + pxmm;

        i = i + 1;


    }
}

和TouchEvent:

public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            float x = event.getX();
            prevx = x;
            System.out.println(x);
            break;
        case MotionEvent.ACTION_MOVE:
            float z = event.getX();
            float dist = z - prevx;
            mainPoint = prevsp + dist;
            closest = mainPoint - ((int)(mainPoint / pxmm)) * pxmm;
            break;
        case MotionEvent.ACTION_UP:
            float y = event.getX();
            prevsp = mainPoint;
            break;
    }

    invalidate();

    return true;
}

在activity_main.xml中,我粘贴此视图的两个副本:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center|top">

<net.manualuser.calibr.TimeScale
    android:id="@+id/my_scale"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white" />

<net.manualuser.calibr.TimeScale
    android:id="@+id/my_scale1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white" />

我应该怎么做才能同步这两个视图,这样当我滚动任何一个缩放时,另一个同时移动。如果我是正确的,我需要为MainActivity中的自定义视图设置OnTouchListener:

TimeScale defScale = (TimeScale)findViewById(R.id.my_scale);
TimeScale defScale1 = (TimeScale)findViewById(R.id.my_scale1);
defScale.setOnTouchListener(this);
defScale1.setOnTouchListener(this);

并编写一些代码以在onTouch方法中同步它们(在MainActivity中)。但我现在知道我该怎么做?

1 个答案:

答案 0 :(得分:0)

要使其正常工作,我需要将事件传递给MainActivity中onTouch的两个视图:

public boolean onTouch(View v, MotionEvent event){
    defScale.onTouchEvent(event);
    defScale1.onTouchEvent(event);
    return false;
}