Tuesday, April 2, 2013

Update custom View at run-time in background thread

Last example demonstrate "drawing on custom View" in onCreate() before the view displayed. It's modified to update the display item in background thread at run-time.

Update custom View at run-time in background thread

The update job is perform in AsyncTask. To request onDraw() of View to be called, your code have to invalidate the view. invalidate() method must be called from a UI thread. To call from a non-UI thread, call postInvalidate().

Modify MainActivity.java from the last exercise.
package com.example.androidgraphview;

import java.util.Random;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;

public class MainActivity extends Activity {
 MyGraphView myGraphView;

 protected void onCreate(Bundle savedInstanceState) {
  myGraphView = (MyGraphView)findViewById(R.id.myview);
  new MyAsyncTask(myGraphView).execute();

 public class MyAsyncTask extends AsyncTask<Void, Void, Void> {

  MyGraphView myTaskView;
  MyAsyncTask(MyGraphView v){
   myTaskView = v;
  protected Void doInBackground(Void... arg0) {
   Random random = new Random();

   for(int i = 0; i <= 500; i++){
    myTaskView.addItem(i, random.nextInt(500));
   return null;


download filesDownload the files.

No comments: