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);
}
,如果它是一个无限循环,然后什么都没显示出来(它应该表现出一个新的随机数每一秒),如果我发起有限循环只有最后一个数字显示,当循环被完成。如何每秒在屏幕上显示一个新的随机数字?
这是不是安全。即使您离开活动,线程仍将运行 – NaviRamyle
尝试更改runOnUiThread()中的TextView值并首先初始化Random。 –