2015-12-02 35 views
1

我的目的很简单,我想创建一个从10到1计数的倒计时。我尝试使用谷歌给出的倒计时,但我不能使它成为一个线程,所以我用这种方式来创建相同的功能,但我有这个code.My应用程序崩溃时,我使用这个线程code.Please帮助我的人。我的应用程序崩溃时,我使用此线程代码

public class MainActivity extends Activity { 
TextView textView; 
Handler handler = new Handler(){ 

    @Override 
    public void handleMessage(Message msg) { 
     // TODO Auto-generated method stub 
     super.handleMessage(msg); 
     String string = textView.getText().toString(); 
     int num = Integer.parseInt(string); 
     num = num-1; 
     string = Integer.toString(num); 
     textView.setText(string); 
    } 

}; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    textView = (TextView) findViewById(R.id.textView); 
} 

@Override 
protected void onStart() { 
    // TODO Auto-generated method stub 
    super.onStart(); 
    Thread myThread = new Thread(new Runnable(){ 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      for(int i = 10; i>0;i--){ 
       try { 
       Thread.sleep(1000); 
       //handler.sendMessage(handler.obtainMessage()); 
       handler.sendMessage(handler.obtainMessage()); 

       } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      } 
     } 
    }); 
    myThread.start(); 

} 



} 
+0

这里是链接我的日志猫,https://photos.google.com/share/AF1QipO-kaTwmY54c70Mk0K67h9sAwA77qLYjoTxClh2jxpUj9uJGeBczYkhvU_TkInLsw/ photo/AF1QipM0O6Q33D-l0x8We0RWskSk_Tt5iNr5iD84cr8T?key = bWZER2lkTkZoNDNYTjJxLXdsYS1pWFFnMzU1WUZR – clicker

+3

您应该将您的实际logcat消息粘贴到您的帖子中。没有在评论中添加链接 – codeMagic

+0

确定兄弟,我得到10个声望 – clicker

回答

1

你的心不是问题与线程,与这些线

String string = textView.getText().toString(); 
int num = Integer.parseInt(string); 

你可能有TextView的开始接触在XML一些文字(“大文本”)。去掉它。 “大文本”不是一个数字,因此当您在该原始字符串上调用parseInt()时,会尝试将“大文本”转换为数字。

试试这个代码:

try { 
    String string = textView.getText().toString(); 
    int num = Integer.parseInt(string); 
    textView.setText(String.valueOf(--num)); 
catch(NumberFormatException ignored){ 

} 

用try/catch块

+0

非常感谢你的兄弟,我爱你。你解决了我的问题! – clicker

+0

随时= p。真高兴你做到了。这是一个很酷的小技巧,我发现不久之前将这个命名空间添加到您的布局XML文件xmlns:tools =“http://schemas.android.com/tools” 现在,如果你想看到文本里面预览,而不是使用android:text =“Large Text”设置实际文本值使用工具:text =“大文本”。当您构建应用程序时,它实际上不会有值,但它会显示在预览中。 –

+0

亚这是很好的信息!赞赏它。我尝试过它,它的工作原理。 – clicker