开发者

Button background before a thread

开发者 https://www.devze.com 2023-04-08 08:22 出处:网络
Why the background of the button doesn\'t change before the thread starts? It changes after the thread sleep ends. I mention that the background changes if there is no thread.

Why the background of the button doesn't change before the thread starts? It changes after the thread sleep ends. I mention that the background changes if there is no thread.

answer1Top.se开发者_运维技巧tBackgroundDrawable(correct);
try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

 //I want to stop this
 playerScTop--;
 playerScoreTop.setText(String.valueOf(playerScTop));


Create a new class extending AsyncTask, pass it the View of which to change the background as well as the two background Drawable instances, then:

  • in onPreExecute() (runs on UI thread), set the first background drawable on your view
  • in doInBackground() (runs on background thread), sleep 2 seconds
  • in onPostExecute() (runs on UI thread), set the other drawable on your view

Untested sample code:

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

    private View view;
    private Drawable background1;
    private Drawable background2;

    public BackgroundChangeTask(View view, Drawable background1, Drawable background2) {
        this.view = view;
        this.background1 = background1;
        this.background2 = background2;
    }

    @Override
    protected void onPreExecute() {
        view.setBackgroundDrawable(background1);
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // too bad
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        view.setBackgroundDrawable(background2);

        // add anything else you want to run "after 2 seconds" here, e.g.
        playerScTop--;
        playerScoreTop.setText(String.valueOf(playerScTop));
    }
}

Invoke from your Activity/Fragment/etc like this (no need to keep the created task around in a field):

new BackgroundChangeTask(BackgroundChangeTask, correct, theOtherDrawable).execute();


answer1Top.setBackgroundDrawable(correct);

new Handler().postDelayed(new Runnable() {

     @Override
     public void run() {
          playerScTop--;
          playerScoreTop.setText(String.valueOf(playerScTop));
     }

}, 2000);
0

精彩评论

暂无评论...
验证码 换一张
取 消