2012-10-29 4 views
0

주기적으로 실행되는 코드 스 니펫을 얻으려고합니다.Handler.postDelayed를 사용하여 여러 Runnables 실행

int endTime = 52; 
final double[] weights = new double[endTime]; 
for (int j = 0; j < endTime; j++) { 
    final int k = j; 
    newWeight = i.integrate(getCarbs(), getProt(), getFat(), newWeight, 
      height, age, PAL, gender, 7); 
    double percentChange = (newWeight - weight); 
    percentChange = percentChange * 100/weight; 
    if(percentChange <-100){ 
     percentChange = -100; 
    } 
    weights[j] = percentChange; 
    final DecimalFormat twoDForm = new DecimalFormat("0.00"); 
    final Handler h = new Handler(); 
    int time = 300*(j); 
    Runnable r = new Runnable() { 
     public void run() { 
      ((TextView) findViewById(R.id.weightGainNumbers)) 
        .setText("Week:\t" + (k + 1) + "\nWeight Change:\t" 
         + twoDForm.format(weights[k]) + "%"); 
      animate(weights[Math.abs(k - 1)], weights[k], false); 
     } 
    }; 
    h.postDelayed(r, time); 
} 

애니메이션은 100 밀리 초를 취
다음은 내 코드입니다. 그러나, 이걸 실행할 때, 응용 프로그램이 멈추고 j = 15 주위에 있어야 할 일을하기 시작합니다. 여기서 무엇이 잘못되었는지를 아는 사람이 있습니까?

+0

활동에서 어디에서 당신이하고 있습니까? – Simon

+0

하나의 "Handler"만 선언하고 for -loop 외부에서 수행하면 어떤 차이가 있습니까? – harism

+0

그것의 onClick에 대한 호출 및 외부 처리기를 이동하면 아무것도 도움이되지 않습니다. – avikar96

답변

1

루프를 반복 할 때마다 새 DecimalFormats를 만드는 등 불필요한 작업을 루프의 반복마다 수행합니다. 또한 하나의 핸들러 만 필요하며 모든 뷰에는 이미 핸들러가 있습니다. 모두 함께하면 더 원활하게 실행됩니다.

첫째, 몇 가지 클래스 변수를 설정 :

final DecimalFormat twoDForm = new DecimalFormat("0.00"); 
TextView weightGainNumbers; 
int weightGainIndex = 0; 
final double[] weights; 

Runnable r = new Runnable() { 
    public void run() { 
     weightGainNumbers.setText("Week:\t" + (weightGainIndex + 1) + "\nWeight Change:\t" 
        + twoDForm.format(weights[weightGainIndex]) + "%"); 

     if(weightGainIndex > 0) 
      animate(weights[Math.abs(weightGainIndex - 1)], weights[weightGainIndex], false); 
     // This animation is a guess, but you get the idea... 
     else 
      animate(0, weights[weightGainIndex], false); 

     weightGainIndex++; 
     // Call the next animation or reset the index for next time 
     if(weightGainIndex < weights.length) 
      weightGainNumbers.postDelayed(r, 300); 
     else 
      weightGainIndex = 0; 
    } 
}; 

다음,onCreate()에서 weightGainNumbers 텍스트 뷰를 초기화합니다.

마지막으로, 사용이 :

int endTime = 52; 
weights = new double[endTime]; 
for (int j = 0; j < endTime; j++) { 
    newWeight = i.integrate(getCarbs(), getProt(), getFat(), newWeight, 
      height, age, PAL, gender, 7); 
    weights[j] = Math.max(percentChange * 100/(newWeight - weight), -100); 
} 
weightGainNumbers.post(r); 

당신이 어떤 구체적인 질문이 있으면 알려주세요.

+0

실행 파일이 클래스 변수 인 경우, 언제 호출됩니까? – avikar96

+0

아, 지금 고쳐 놨어. 내가 정말로 이걸 스스로 실행할 수 없기 때문에 다른 어떤 멍청이든지 알려줘. – Sam

+0

정말 고마워! 이제 작동합니다. – avikar96

관련 문제