[英]Android: Button method works only once
I'm pretty new to Android's Java (so please don't beat me up) and I have a question to my button action. 我对Android的Java很陌生(所以请不要打扰我),我对按钮操作有疑问。 The called method is running only one time.
被调用的方法仅运行一次。 When I click the button the second time nothing happens anymore.
当我第二次单击按钮时,什么也没有发生。 I do not understand why.
我不理解为什么。 No errors, no flaws, the method is doing what is expected.
没有错误,没有缺陷,该方法正在完成预期的工作。 Any hints?
有什么提示吗? Thanks!
谢谢!
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView mainFortuneTextView;
Button mainFortuneButton;
private int counter, i, x;
//private int randomNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 1. Access the TextView defined in layout XML
// and then set its text
mainFortuneTextView = (TextView) findViewById(R.id.fortuneTextView);
// 2. Access the Button defined in layout XML
// and listen for it here by using "this"
mainFortuneButton = (Button) findViewById(R.id.fortuneButton);
mainFortuneButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// happens on button action in main view
runThread();
Random rnd = new Random();
x = rnd.nextInt(11) + 1;
}
private void runThread() {
mainFortuneButton.setEnabled(false);
new Thread() {
public void run() {
while (i++ < 10) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
mainFortuneTextView.setText("#" + i);
}
});
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// activate button again
runOnUiThread(new Runnable() {
@Override
public void run() {
mainFortuneButton.setEnabled(true);
}
});
}
}.start();
}
}
Your variable i
used in your while is a field. i
在您期间使用的变量是一个字段。 That means that it will not reset. 这意味着它将不会重置。 That's why the second time you call your thread the
i
value will be 10 and it will be called not again. 这就是为什么第二次调用线程时,
i
值为10,并且不会再次调用它。 You have to reset your i
again before starting a new thread. 在开始新线程之前,您必须再次重置
i
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.