So I wanted to implement Timer in my Anroid program and I found out the better way to do that is using Handler class.
First I decided to write the simplest program using Handler - the text is set after 1 second. I'm totall beginner in Android, so I went through some tutorials on web especially that one http://developer.android.com/resources/articles/timed-ui-updates.html , but still my application shows error ("application mTimer stopped").
So could anyone point out where exactly am I making mistake? I would be gratefull, here's the code:
public class mTimer extends Activity {
TextView tv;
Button button1,button2;
Handler mHandler;
private Runnable myTask = new Runnable() {
public void run() {
tv.setText("text");
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.textView1);
b开发者_如何学编程utton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.postDelayed(myTask, 100);
}
});
}
}
You should initialize your Handler
in your onCreate
method with at least a code like mHandler = new Handler();
.
Note, that the myTask
task will be run on the UI thread, since your handler is declared there
API Docs for Handler.postDelayed
:
The runnable will be run on the thread to which this handler is attached.
精彩评论