2011-11-18 138 views
4

這是一個奇怪的行爲,我不明白自定義視圖。我在框架佈局中有兩個視圖,一個在另一個之上。的觀點很簡單,我做了他們只是一個簡短的測試Android onDraw()在所有視圖上執行?

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 { 
     } 
    } 
} 

和視圖2

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的?

以後編輯 View2有一個很大的圖像繪製,圖像旋轉和縮放根據一些保存的喜好。通常,當我開始Activity時,View2.onDraw()負責旋轉,轉換和縮放位圖並在畫布上繪製它。當用戶觸摸View1時,我只需要執行View1.onDraw(),因爲對於每次用戶交互,都沒有必要一遍又一遍地重繪同一個背景圖像。如何停止View2.onDraw()執行?

回答

1

我想這應該回答你的問題:

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

「當事情已經改變已經失效這一觀點父母的孩子的佈局稱這將安排的佈局傳遞視圖樹「。

+0

我已經編輯了一些問題。 Pleare閱讀後期編輯部分,也許你有一個想法。謝謝您的回答。 – Alin

+0

您是否嘗試過在View1中調用繪圖而不是updateDrawings?不知道會發生什麼。 –

+0

我目前正在測試setWillNotDraw(true)以查看是否停止向前發送invalidate。 – Alin