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

时间:2015-09-28 05:08:33

标签: java android

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);
}

}

如果它是一个无限循环,那么什么都没有出现(它应该每秒显示一个新的随机数),如果我启动一个有限循环,只有最后一个数字显示循环结束时。如何在屏幕上每秒显示一个新的随机数?

2 个答案:

答案 0 :(得分:1)

  

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

rand的{​​{1}}对象为Random。在调用null方法之前初始化它:

nextInt

修改

因为从Thread的run方法访问TextView会导致rand = new Random(); int y=rand.nextInt(100); 所以换行:

Only the original thread that created a view hierarchy...

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

答案 1 :(得分: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);
}