Friday, May 8, 2015

Don't try to start a new Thread and change UI within onCreate() or onResume() methods,

If you try to start a new Thread and change UI within onCreate() or onResume() methods, it's not guaranteed that they will be called.

Do it in a trigger method.


package com.digitalturbine.helloworld;
import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    TextView tvMain;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        tvMain = (TextView) findViewById(R.id.tvMain);

    }


    public void changeText(View view) {
        Runnable runnable = new Runnable() {
            @Override            public void run() {
                tvMain.postDelayed(new Runnable() {
                    @Override                    public void run() {
                        tvMain.setText("Changed from another thread.");                    }
                }, 3000);            }
        };
        new Thread(runnable).start();    }

}

No comments:

Post a Comment