2011-11-18 134 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