Rocky
Rocky

Reputation: 1287

Android:Operate UI controls in other thread,but

beginButton.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        PlayThread playThread = new PlayThread();
        Thread thread = new Thread(playThread);

        thread.start();
    }
});

public class PlayThread implements Runnable {
    @Override
    public void run() {
        beginButton.setClickable(false);
        pauseButton.setClickable(true);
        messageBool = true;
        int maxProgressBar = playProgressBar.getMax();
        int currentInt = playProgressBar.getProgress();

        for(; currentInt <= maxProgressBar; ++currentInt)
        {
            if(messageBool == false)
            {
                break;
            }
            playProgressBar.incrementProgressBy(1);
            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if(currentInt > maxProgressBar)
        {
            playProgressBar.setProgress(0);
            beginButton.setClickable(true);
            pauseButton.setClickable(false);
        }
    }
};

Hi,everyone. Is there any problem about this code? I know we cannot operate the UI's controls in other threads except UI thread . But this code runs OK.So what's wrong or is there something I miss? Thanks in advance!

Upvotes: 0

Views: 82

Answers (1)

user
user

Reputation: 87064

You're safe if you don't modify the View in such way that it needs to be redrawn on the screen. setClickable only modifies one of its properties if you were, for example, to set the text or modify the LayoutParams of that View, action which will invalidate the View, the dreaded exception Touched from the wrong thread...etc will appear.

The ProgressBar is thread safe and can be used from any thread.

Upvotes: 1

Related Questions