2015-09-28 127 views
-6
public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    /* runOnUiThread th=new runOnUiThread(new TextChange());*/ 
    final TextView tv=(TextView)findViewById(R.id.tv); 


      runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 

      while(true) 
      { 
       try { 
        Thread.currentThread().sleep(1000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       Random rand = new Random(); 
       int y=rand.nextInt(100); 
       tv.setText(Integer.toString(y)); 

      } 
     } 
    }); 


} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

}我想每秒打印一个随机数,但没有出现?

,如果它是一个无限循环,然后什么都没显示出来(它应该表现出一个新的随机数每一秒),如果我发起有限循环只有最后一个数字显示,当循环被完成。如何每秒在屏幕上显示一个新的随机数字?

+0

这是不是安全。即使您离开活动,线程仍将运行 – NaviRamyle

+1

尝试更改runOnUiThread()中的TextView值并首先初始化Random。 –

回答

1

我想每秒打印一个随机数。为什么程序 会崩溃?

由于Randomrand目的是null。调用nextInt方法之前初始化:

rand = new Random(); 
int y=rand.nextInt(100); 

编辑:

因为从线程的run方法访问的TextView,这将导致Only the original thread that created a view hierarchy...所以包装:

runOnUiThread方法或使用 Handler
tv.setText(Integer.toString(y)); 

+0

谢谢,现在至少它显示第一个数字,但它再次坠毁@ρяσѕρєяK –

+0

说只有创建视图层次结构的原始线程可以触及其视图,问题在 –

+0

tv.setText(Integer.toString(y)) ; –

0

尝试:

Random rand = new Random(); 
int y=rand.nextInt(100); 

更好的办法:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final TextView tv=(TextView)findViewById(R.id.tv); 

    final Handler handler = new Handler(); 
    final Random random = new Random(); 
    Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      int y = random.nextInt(100); 
      tv.setText(Integer.toString(y)); 
      handler.postDelayed(this, 1000); 
     } 
    }; 
    handler.post(runnable); 
} 
+0

不会我们需要一个runOnUiThread东西在这里改变textview @subhash –

+0

处理程序在它发布的同一个线程上运行,所以我们不需要在uiThread上运行。以上代码工作,为什么不试试它。 – subhash