Reputation: 25
I have a problem with a pice of code:
// Feld 1 OnClick int punkte;
int punkte;
punkte=0;
TextView counter = (TextView) findViewById(R.id.counter);
counter.setText(Integer.toString(punkte));
TextView next = (TextView) findViewById(R.id.Farbent1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
punkte=punkte+1;
};
});
When I ask eclipse it says that I have to do my "punkte" in the public void onClick(View View) to final int. But when it is final I cant change the variable I can't see the reason why I have to do my variable final. And is there a solution to change my variable in onClick(View View)? best regrads nameless
Upvotes: 0
Views: 96
Reputation: 11782
The variable's scope is limited to the function that you declare all of this in (presumably onCreate()
? ). This means that the variable would normally get destroyed at the end of the function (making it inaccessible to your onClick listener), but if you declare it as final, the compiler can, in a sense, cheat and keep it around. If you want to maintain the variable for use outside of your function, it needs to be a class variable.
public class MyClass extends Activity{
private int punkte = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Do stuff ...
TextView counter = (TextView) findViewById(R.id.counter);
counter.setText(Integer.toString(punkte));
TextView next = (TextView) findViewById(R.id.Farbent1);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
punkte=punkte+1;
}
});
}
}
Upvotes: 1
Reputation: 6591
In order to refer to a local variable inside of a callback (the onClick() method) that variable has to be declared "final" so that the compiler knows that the reference to it won't change.
You can work around this easily by making punkte a class-level field.
private int punkte = 0;
private void myMethod(){
TextView counter = (TextView) findViewById(R.id.counter);
counter.setText(Integer.toString(punkte));
TextView next = (TextView) findViewById(R.id.Farbent1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
punkte=punkte+1;
};
});
}
Upvotes: 2