2010年5月23日星期日

要強制重繪View,調用invalidate()

本例子會在onTouchEvent()之內處理ACTION_UP, ACTION_DOWN 和 ACTION_MOVE 事件. 當用戶觸摸(ACTION_MOVE)或移動(ACTION_DOWN), R.drawable.icon會顯示和跟隨移動. 這是通過event.getX()和event.getY()獲得事件位置, 然後通過調用invalidate()強制重繪View.

要強制重繪View,調用invalidate()

繼續使用上一篇文章"處理自定義視圖的事件(Event)"的程序代碼, 修改MyView.java
package com.AndroidView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class MyView extends View {

private Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Context myContext;
Bitmap myBitmap;

private int locX, locY;
private int offX, offY;
private boolean showImage = false;

public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
init(context);
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init(context);
}

public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init(context);
}

private void init(Context context){
myContext = context;
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
offX = myBitmap.getWidth()/2;
offY = myBitmap.getHeight()/2;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);

setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
//super.onDraw(canvas);

if (showImage){
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(myBitmap, locX-offX, locY-offY, null);
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub

int action = event.getAction();

if ((action == MotionEvent.ACTION_DOWN)||
(action == MotionEvent.ACTION_MOVE)){
locX = (int)event.getX();
locY = (int)event.getY();
showImage = true;
invalidate();
}
else if (action == MotionEvent.ACTION_UP){
showImage = false;
invalidate();
}


return true;
}

}




沒有留言:

發佈留言