简体   繁体   中英

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. 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. 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. You have to reset your i again before starting a new thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM