调用onWindowFocusChange()后更改文本

问题描述 投票:0回答:1

我正在尝试制作一个格斗屏幕,我有两个精灵,并且在它们之上我有健康栏,其健康点被写入(ProgressBar上面有TextView)。我也有一个AnimationDrawable。它是在onWindowsFocusChanged()内部启动的。我希望在动画之后将progressBar前面的文本更改。因此,例如,在动画之前,一个条形码已写入150/150,并且在动画之后我希望它变为例如80/150。问题是,每当我尝试调用setText时,应用程序崩溃(我猜因为onWindowFocusChanged是最后调用的东西)。有没有办法做到这一点?

这是我的代码片段(number_one.start()是动画的开头):

private void health_bars(int points_one, int points_two){

    healthBarOne.setMax(MAX_HEALTH);
    healthBarOne.setProgress(points_one);
    health_points_one.setText(points_one + "/" + MAX_HEALTH);

    healthBarTwo.setMax(MAX_HEALTH);
    healthBarTwo.setProgress(points_two);
    health_points_two.setText(points_two + "/" + MAX_HEALTH);

}




public void onWindowFocusChanged(final boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus){
        Thread th = new Thread(){
            public void run(){
                number_one.start();
                try {
                    Thread.sleep(2000);
                } catch(InterruptedException e){
                }
                health_bars(new_health_one, new_health_two);

                try {
                    Thread.sleep(2000);
                } catch(InterruptedException e){
                }
                finish();
            }
        };
        th.start();
        attackAnimation();
    }
}

感谢您的时间!

编辑:Error Log

java android
1个回答
1
投票

您无法从UI之外的任何其他线程更新UI元素。这基本上就是错误所说的。要解决此问题,请在Android中使用runOnUiThread方法:

Thread th = new Thread(){
        public void run(){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        health_bars(new_health_one, new_health_two);
                    }
                });
       }
      }
© www.soinside.com 2019 - 2024. All rights reserved.