所有的视图都会执行Android onDraw()方法吗?

5

这里有一个奇怪的行为,关于自定义视图我不太理解。我在帧布局中放置了两个视图,一个在另一个之上。这些视图很简单,我只是为了进行短暂的测试而制作它们。

public class View1  extends View  {
....

    @Override
     public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN){
            this.updateDrawings();
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (canvas != null) 
        {
            Log.i("Test", "Draw View1");
        }
    }

    public void updateDrawings() {
        try {
            this.invalidate();
        }
        finally {
        }
    }
}

以及 View2

public class View2  extends View  {
....

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (canvas != null) 
        {
            Log.i("Test", "Draw View2");
        }
    }

    public void updateDrawings() {
        try {
            this.invalidate();
        }
        finally {
        }
    }
}

将所有内容都放在FrameLayout上,不会出现错位。

<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:background="#ffffff">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1">

            <com.View2
                android:layout_centerInParent="true"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginBottom="5dip" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1">

            <com.View1
                android:layout_centerInParent="true"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginBottom="5dip" />
        </LinearLayout>
</FrameLayout>

我的问题是:为什么从View1的onTouch方法执行时,两个视图的onDraw()方法都会执行?为什么不仅仅只有View1的呢?
稍后编辑:View2有一个大图片要绘制,该图片根据一些保存的偏好进行旋转和缩放。通常情况下,当我启动Activity时,View2.onDraw()会负责旋转、平移和缩放位图,并将其绘制在画布上。当用户触摸View1时,我希望只执行View1.onDraw(),因为每个用户交互都重新绘制相同的背景图片没有意义。如何停止View2.onDraw()的执行?
1个回答

1

我稍微编辑了问题,请阅读“后续编辑”部分,也许您有想法。感谢您的回答。 - Alin
你尝试在View1中调用draw而不是updateDrawings了吗?虽然不知道会发生什么。 - Jordy Langen
我目前正在测试 setWillNotDraw(true) 以查看是否停止向前发送 invalidate。 - Alin
setWillNotDraw会停止视图绘制,但在这种情况下,背景图片会消失... - Alin
是因为你在构造函数或其他地方调用了setWillNotDraw(true)吗? - Jordy Langen
实际上,当一个视图无效并将无效发送到树中的其余视图时,如果一个视图设置了setWillNotDraw(true),那么结果就是当该视图被无效时,它不会重新绘制并保持为空。当您不希望背景视图重新绘制但又不可见时,这非常有用。 - Alin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接