Reputation: 97
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
Upvotes: 1
Views: 857
Reputation: 7083
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
.
Upvotes: 2
Reputation: 44571
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.
Upvotes: 0