I have created an app composed of one single activity which include a single TextView
. Here is the XML of my activity :
activity_main.xml
Your run()
method will be called on a background thread, and it cannot manipulate the UI as a result.
A lighter-weight solution would be:
public class MainActivity extends AppCompatActivity {
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text_1);
onEverySecond.run();
}
private Runnable onEverySecond=new Runnable() {
@Override
public void run() {
text.setText("test");
text.postDelayed(this, 1000);
}
}
}
postDelayed()
calls your run()
method on the main application thread, after the designated delay period. Here, we use that to have the Runnable
schedule itself to run again after 1000ms.
To stop the postDelayed()
"loop", call removeCallbacks(onEverySecond)
on your MainActivity
.
The advantage of this over using runOnUiThread()
inside the TimerTask
is that it is less expensive, as you are not creating a separate thread (the Timer
/TimerTask
thread).
You need to perform
text.setText("test");
in UI thread. You can do so using Handlers.
final Handler myHandler = new Handler();
myHandler.post(myRunnable);
final Runnable myRunnable = new Runnable() {
public void run() {
text.setText("test");
}
};