2014-01-31 22 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()? –