android development tutorial for handler asynchronous update ui

  • 2020-05-24 06:11:02
  • OfStack

In fact, the word game program is very simple, is 1 view and 1 Activity, under the use of handier and postInvalidate() update UI

Calling the Handler.post (Runnable r) method,Runnable runs in the thread where UI lives, so you can call View.invalidate () directly


packagecom.Test.androidtest;
importandroid.app.Activity;
importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.View;
publicclassTestHandlerextendsActivity{
privateMyViewmyView;
privateHandlermHandler;
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
myView=newMyView(this);
mHandler=newHandler();
mHandler.post(newRunnable(){
@Override
publicvoidrun(){
myView.invalidate();
mHandler.postDelayed(this,5);
}
});
setContentView(myView);27}
classMyViewextendsView{30privatefloatx=0f;31publicMyView(Contextcontext){
super(context);33
}
protectedvoidonDraw(Canvascanvas){
super.onDraw(canvas);37x+=1;
PaintmPaint=newPaint();
mPaint.setColor(Color.BLUE);
canvas.drawRect(x,
,x+40,80,mPaint);41}
}
}

Update UI in a new thread, postInvalidate()


publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
myView=newMyView(this);
this.setContentView(this.myView);
newThread(newmyThread()).start();
}
classmyThreadimplementsRunnable{
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
try{
myView.postInvalidate();
Thread.sleep(100);
}catch(InterruptedExceptione){
Thread.currentThread().interrupt();
}
}
}
}


Related articles: