Android onDraw () выполняется во всех представлениях? - PullRequest
5 голосов
/ 18 ноября 2011

Вот странное поведение, которое я не понимаю в пользовательских представлениях. У меня есть два вида в макете кадра, один поверх другого. Представления просты, и я сделал их только для короткого теста

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>

Мой вопрос: почему при выполнении onTouch из View1 выполняется метод onDraw () обоих представлений? Почему не только View1's?

Позже Редактировать View2 имеет большое изображение для рисования, изображение поворачивается и масштабируется в соответствии с некоторыми сохраненными предпочтениями. Обычно, когда я запускаю Activity, View2.onDraw () заботится о вращении, переводе и масштабировании растрового изображения и рисовании его на холсте. Когда пользователь касается View1, я хочу, чтобы только View1.onDraw () выполнялся, потому что нет смысла перерисовывать одно и то же фоновое изображение снова и снова для каждого взаимодействия с пользователем. Как остановить выполнение View2.onDraw ()?

1 Ответ

1 голос
/ 18 ноября 2011

Я думаю, что это должно ответить на ваш вопрос:

http://developer.android.com/reference/android/view/ViewParent.html#requestLayout()

"Вызывается, когда что-то изменилось, что сделало недействительным макет дочернего элемента этого родителя представления. Это запланирует компоновкупроход дерева просмотра. "

...