Reputation: 23
i coded this lines to change textview1 Continuous when user clicked button but it sucks at value 1 in output why :\
public class dobeyti extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dobeyti);
final TextView tView;
Button mButton;
tView = (TextView)findViewById(R.id.textView1);
mButton = (Button)findViewById(R.id.button);
assert mButton != null;
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = 0;
num++;
tView.setText(Integer.toString(num));
}
});
}
}
Upvotes: 1
Views: 96
Reputation: 15087
Becuase you defined the num value inside the onclick method so it will be reassigned to 0 every time.
Just put int num=0
outside the method like below:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dobeyti);
final TextView tView;
Button mButton;
tView = (TextView)findViewById(R.id.textView1);
mButton = (Button)findViewById(R.id.button);
assert mButton != null;
mButton.setOnClickListener(new View.OnClickListener() {
int num = 0;
@Override
public void onClick(View v) {
num++;
tView.setText(Integer.toString(num));
}
});
}
}
Upvotes: 2
Reputation: 447
Move int num = 0; outside OnClickListener. Every time you click button value on variable num is set to 0 -> increased to 1 and set as text, that is why it stuck at 1.
int num = 0;
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
num++;
tView.setText(Integer.toString(num));
}
});
}
}
Upvotes: 0