[英]Android Using Thread Properly. Randomize Pop out image continuously
Continuously changing imageview image on start of activity. 活动开始时不断更改imageview图像。 Will it be possible without using Thread?if not at least tell me how to use Thread properly and how should I initiate it.
如果没有至少使用Thread,是否可以使用Thread?如果不告诉我如何正确使用Thread,以及如何启动它。 Please.,
请。,
It's for a whack a mole like android game. 这是为像安卓游戏一样mole鼠。
I tried to do simple display of random text but did not work. 我试图对随机文本进行简单显示,但是没有用。
public class NewGame extends Activity {
gameThread gameOn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newgame);
hView = (TextView) findViewById(R.id.HammersText);
gameOn = new gameThread();
gameOn.start();
}
}
public class gameThread extends Thread
{
NewGame gameOn;
public void run() {
super.run();
Random ramhole = new Random();
int hole = ramhole.nextInt(8);
Random ramletter = new Random();
int letter = ramletter.nextInt(26);
gameOn = new NewGame();
gameOn.hView.setText("Hole = "+hole+"Letter = "+letter);
}
}
Please help me out on this. 请帮助我。
Use a countdownTimer instead of Thread 使用countdownTimer而不是Thread
new CountDownTimer(9000000, 5000) {
public void onTick(long millisUntilFinished) {
Random ramhole = new Random();
int hole = ramhole.nextInt(8);
Random ramletter = new Random();
int letter = ramletter.nextInt(26);
hView.setText("Hole = "+hole+"Letter = "+letter);
}
public void onFinish() {
//Restart timer if you want.
}
}.start();
You can still do with Threading but its a overkill for what you are trying to do. 您仍然可以使用Threading进行操作,但这对您尝试执行的操作而言是过大的选择。 Also in your case, you cannot do
同样在你的情况下,你不能做
gameOn = new NewGame();
Activity always needs to be initialized by framework. 活动始终需要由框架初始化。 And setText api should always be called from Ui thread.
并且应该始终从Ui线程调用setText api。 Maybe that is why your app is not working
也许这就是为什么您的应用无法正常工作的原因
You should only be touching the UI on the main UI thread, so if you do decide to use threads, then you should look at the AsyncTask . 您应该只在主UI线程上触摸UI,因此,如果您决定使用线程,则应查看AsyncTask 。
If it was my game, I would start a new AsyncTask for each hole. 如果是我的游戏,我将为每个漏洞启动一个新的AsyncTask。 In doInBackground it would sleep for some random amount of time, then it would publish progress.
在doInBackground中,它将休眠一段时间,然后发布进度。 In every even onProgressUpdate it would show the mole.
在每个甚至onProgressUpdate中,它都会显示痣。 In every odd onProgressUpdate it would hide the mole (if it hasn't been whacked.) By handling the show/hide in onProgressUpdate you are automatically on the main UI thread so no worries there, and having a separate thread for each hole will allow you to have a more dynamic playing field of holes/moles.
在每个奇数的onProgressUpdate中,它都会隐藏痣(如果尚未被捣破。)通过在onProgressUpdate中处理显示/隐藏操作,您将自动进入主UI线程,因此无需担心,并且每个孔都有一个单独的线程将允许您将拥有更加动态的洞/摩尔运动场。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.