简体   繁体   中英

Updating textView in Android Studio

I have a textView set up on my main activity, and a button. When I click the button, I'd like the textView to start updating it's value based on the code below. However, this doesn't work and the problem is the loop. Can someone explain why? I am new to Java and Android Development

button2 = (Button) findViewById(R.id.button);
    button2.setOnClickListener(new OnClickListener() {
        TextView textView = (TextView)findViewById(R.id.refView);
        public void onClick(View arg0) {
            for(i=1;i<1;i++){
              i = i + 1;
            textView.setText(String.valueOf(i)+"hello");
            }
        }
    });

Thank You

Try this:

TextView textView = (TextView)findViewById(R.id.refView);
button2.setOnClickListener(new View.OnClickListener() {
            int i = 0;
            public void onClick(View arg0) {
                i = i + 1;
                textView.setText(String.valueOf(i)+"hello");
            }
        });

Your for loop conditions were wrong. for(i=1;i<1;i++) won't even start, because 1<1 is already met. Initiate count variable i before onClick and then update it before click and set new text with updated i .

Not sure what exactly you want to happen. But, you can get rid of this line

i = i + 1;

because the i++ already increments i by 1 with each iteration of the for loop .

Second, since i starts off at 1 and you want the loop to run while i<1 , it will never enter the loop . It is never less than 1.

Third, if the conditions were different, say

for (int i=0; i<10; i++)

it will run through the loop so fast that you won't even recognize a change.

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