2015-01-11 2 views
1

내 스레드에서 textView를 변경하려고하지만 항상 충돌합니다. 왜?스레드에서 TextView 텍스트를 변경할 수 없습니다.

public void startProgress(View view) { 

    bar.setProgress(0); 
    new Thread(new Task()).start(); 
} 

class Task implements Runnable { 
    @Override 
    public void run() { 
     for (int i = 0; i <= 10; i++) { 
      final int value = i; 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      bar.setProgress(value); 
      text.setText("i = "+i); 
     } 
    } 
} 

나는 왜 내가 그것을 바꿀 수 있는지 모른다. 왜 그 사람이 누군지 압니까?

감사합니다.

+0

몇 가지 상황 (예 : 'ProgressBar')을 제외하고는 백그라운드 스레드에서 활동 또는 프래그먼트의 UI를 수정할 수 없습니다. – CommonsWare

답변

0

보기는 상위 스레드 만 수정할 수 있습니다. 이것은 사람들이 직면하는 공통적 인 문제이며, 불행히도 그 문제를 해결해야합니다.

0

사용 runOnUiThread @dodo으로

runOnUiThread(new Runnable(){ 
    public void run() { 
     for (int i = 0; i <= 10; i++) { 
      final int value = i; 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
      e.printStackTrace(); 
      } 
      bar.setProgress(value); 
      text.setText("i = "+i); 
     } 
    } 
}); 
+0

runOnUiThread를 사용하면 작동하지만 루프가 끝나면 내용이 업데이트됩니다. "startProgress"를 활성화 한 후 10 초 동안 UI를 터치 할 수 없습니다 (루프가 지속되는 시간). i = 10으로 변경된 텍스트가 표시되지만 UI가 블 루킹되는 동안 UI가 변경됩니다. – user2911701

0

또는 @CommonsWare는 메인 UI 스레드에서보기 hiearhcy에 액세스해야했다. 는이 규칙을 준수

new Handler(context.getMainLooper()).post(new Runnable() { 
    public void run() { 
     bar.setProgress(value); 
     text.setText("i = "+i); 
    } 
}); 
0

Handler.post (Context.getMainLooper()) 마지막으로 내가 그것을 고정 사용합니다. 어쨌든 고마워.

public void startProgress(View view) { 

    bar.setProgress(0); 
    //new Thread(new Task()).start(); 

    Thread th = new Thread(new Runnable() { 
     public void run() { 
      for (int i=0; i<10;i++){   
       final int timer = i; 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         text.setText("velocitat: "+timer); 
        } 
       }); 
       bar.setProgress(timer); 
       try { 
        Thread.sleep(1000); 
       } 
       catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }); 
    th.start(); 
} 
관련 문제