Breaking News
Loading...
Tuesday, 2 April 2013

Update custom View at run-time in background thread

14:50
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;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
}

@Override
protected Void doInBackground(Void... arg0) {
Random random = new Random();

for(int i = 0; i <= 500; i++){
myTaskView.addItem(i, random.nextInt(500));
myTaskView.postInvalidate();
SystemClock.sleep(100);
}

return null;
}

}

}


download filesDownload the files.

0 comments:

Post a Comment

 
Toggle Footer