2014-01-31 23 views
0

我是新來的android和我想做一個簡單的例子,我點擊一個開始按鈕和另一個活動是打開的,有一個簡單的數字開始在一個和向上計數,但我面臨一個問題,我初始化onCreate方法(在第二個活動)的一些變量後,我應該在哪裏實際啓動while語句來計算和修改文本視圖?後onCreate Android

我寫了這個類:

public class Counter extends Thread{ 

    private TextView tv; 
    private int i; 


    public Counter(TextView tv){ 
     this.tv = tv; 
    } 

    @Override 
    public void run() { 
     while(true){ 
      tv.setText(i); 
      try { 
       sleep(500); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      i++; 
     } 
    } 

並開始線程在這裏:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_game); 
      counter = new Counter((TextView) findViewById(R.id.textView2)); 
      counter.start(); 
} 
+6

你的代碼在哪裏?你試過了什麼? –

+0

我發佈了一些代碼,我寫了 –

+0

如果我得到你的問題然後在裏面做onResume() –

回答

0

我發現我需要從類似的帖子,處理程序是必需的,因爲只有UI線程可以更新用戶界面。

private void countNumbers() { 
    final TextView numbers = (TextView) findViewById(R.id.textView2); 


    final Handler handler = new Handler(); 
    Runnable runnable = new Runnable() { 
     public void run() { 
      int i = 0; 
      while (i++ < 500) { 
       try { 
        Thread.sleep(10); 
       }  
       catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       final int j = i; 
       handler.post(new Runnable(){ 
        public void run() { 
         numbers.setText(Integer.toString(j)); 
       } 
      }); 
      } 
     } 
    }; 
    new Thread(runnable).start(); 
} 

在onCreate()中調用countNumbers()方法。

0
@SuppressLint("UseValueOf") 
final Handler handler = new Handler(); 
     handler.post(new Runnable() { 
      @Override 
      public void run() { 
       // change your text here 
       if (condition) { 
        i++; 
        txt_TimeRecord.setText("" + i); 
       } else { 
        i = 0; 
       } 
       handler.postDelayed(this, 1 * 1000L); 
      } 
     }); 

[格式化代碼正確]

+0

http://meta.stackexchange.com/questions/148272/is-there-any-benefit-to-allowing-code-only-answers-while-blocking-code-only-ques。請加一些解釋也 – Raghunandan

+0

嗯謝謝下一次我會記住,真的很抱歉fot這種行爲我的老人 –

0
//In first activity 
//set onclick method to that button. 

public void onclick(view v) 
{ 
     Intent intent = new Intent(this, secondactivity.class); 
     startActivity(intent); 
} 

// in second activity in 
// initi i value. 

while(i<10) 
{ 
    i++ ; 

// sleep statement 
//print that i in textview 

}

+0

我應該把哪一種方法把while語句? –

+0

放在onresume。 – Lingeshwaran

+0

並在數字之間添加一些時間?Thread.sleep()? –