Monday, May 5, 2014

How did the ball movement


I want to draw a small ball movement on the screen, the results did not respond
 
package com.example.systemaction;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

public class BallActivity extends Activity {

@ Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
MyView v = new MyView (this, null);
setContentView (v);
}

class MyView extends View implements Runnable {

private int cx = 20, cy = 20;

public MyView (Context context, AttributeSet attrs) {
super (context, attrs);
setFocusable (true);
. new Thread (this) start ();
}

@ Override
public void run () {
Looper.prepare ();
ReFreshHandle handler = new ReFreshHandle ();
while (! Thread.currentThread (). isInterrupted ()) {
/ / Send the message to update the interface
Message message = new Message ();
message.what = 0x101;
handler.sendMessage (message);
try {
Thread.sleep (100);
} Catch (InterruptedException i)
{
i.printStackTrace ();
}
}
Looper.loop ();
}

/ / Draw a small ball
@ Override
protected void onDraw (Canvas canvas) {
super.onDraw (canvas);
Paint paint = new Paint ();
paint.setColor (Color.GREEN);
canvas.drawCircle (cx, cy, 10, paint);
}

/ / Update interface processor
class ReFreshHandle extends Handler {

@ Override
public void handleMessage (Message msg) {
if (msg.what == 0x101) {
MyView.this.update ();
MyView.this.invalidate ();
}
super.handleMessage (msg);
}
}

/ / Update the coordinates of ball movement
public void update () {
int h = getHeight ();
cy + = 5;
if (cy> = h) {
cy = 20;
}

}
}
}
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
You print your thread under the look did not start.
Reply:
The ReFreshHandle handler = new ReFreshHandle ();
Put out, do not put run in

Reply:
reference to the second floor hjywyj reply:
will ReFreshHandle handler = new ReFreshHandle ();
Put out, do not run into the inside
ah, I really was not careful, thank you

No comments:

Post a Comment