天天看點

【具體問題】Only the original thread that created a view hierarchy can touch its views

timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (!isSeekBarChanging){
                            currentPosition = mediaPlayer.getCurrentPosition();// 記錄目前播放位置
                            seekBar.setProgress(currentPosition);
                            tv_current_position.setText(currentPosition+"");
                        }
                    }
                },0,1000);
           

問題出在這裡:

tv_current_position.setText(currentPosition+"");

此時是在子線程中,要轉移到UI線程中設定

那如何在UI線程中動态設定

textview的值呢?

通過handle實作:

private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            tv_current_position.setText(currentPosition+"");
        }
    };

timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (!isSeekBarChanging){
                            currentPosition = mediaPlayer.getCurrentPosition();// 記錄目前播放位置
                            seekBar.setProgress(currentPosition);
                            // 發送消息,通知UI線程重新整理視圖
                            handler.sendEmptyMessage(0);
                        }
                    }
                },0,1000);