I am developing an app in which I would like to display a view when a touch event is registered. The problem is the view will not display and my code become unresponsive.
Here is my view:
public class TouchFX extends View {
RectF oval;
float Tx, Ty;
Paint paint;
int longSide, numRun;
float top, left, right, bottom;
boolean removable;
public TouchFX(Context context) {
super(context);
// TODO Auto-generated constructor stub
Tx = TouchService.x;
Ty = TouchService.y;
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStrokeJoin(Paint.Join.ROUND);
numRun = 0;
removable = false;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (canvas.getWidth() > canvas.getHeight())
longSide = canvas.getWidth();
else
longSide = canvas.getHeight();
if (numRun == 0) {
left = Tx - (longSide / 15);
top = Ty + (longSide / 15);
right = Tx + (longSide / 15);
bottom = Ty - (longSide / 15);
} else if (numRun <= 8) {
left += 2;
top += 2;
right += 2;
bottom += 2;
}
oval = new RectF(left, top, right, bottom);
if (numRun < 9)
canvas.drawArc(oval, 0, 360, false, paint);
else
removable = true;
numRun++;
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is my onTouch handler:
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (v == tv && event.getAction() == MotionEvent.ACTION_DOWN
&& isRunning == true) {
x = event.getX();
y = event.getY();
tfx = new TouchFX(this);
winmngr.addView(tfx, lpFX);
//Do some stuff, make some Toasts
while(!tfx.removable) {
//waiting for animation to end
}
winmngr.removeView(tfx);
}
return false;
}
Now, obviously it’s getting stuck within the while loop, but why isn’t it drawing the arc and updating the boolean?
it is getting stuck because onTouch event operates in UI thread (so as onDraw). So you are blocking your UI thread in
whileloop and onDraw() doesn’t get processor time.Consider using callback mechanism, so
removeView()routines is triggered by youronDrawmethod. Alsosleep(400)in UI thread is extremely bad idea. You can try to use handler and do post delayed execution: