这是我不了解自定义视图的奇怪行为。我在框架布局中有两个视图,一个在另一个之上。视图很简单,我制作它们只是为了做一个简短的测试
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 的?
后来Edit View2有一张大图要画,根据一些保存的喜好旋转和缩放图片。通常,当我启动 Activity 时,View2.onDraw() 负责 Bitmap 的旋转、平移和缩放并将其绘制在画布上。当用户触摸 View1 时,我只希望 View1.onDraw() 执行,因为没有必要为每个用户交互一遍又一遍地重绘相同的背景图像。如何停止 View2.onDraw() 执行?