I have some code like this:
final int height = 0; //I want to get this height after Predraw view
view.addOnPreDrawListener(new OnPreDrawListener()
{
@Override
public boolean onPreDraw()
{
int myHeight = itemLayout.getMeasuredHeight();
height = myHeight; //this line has error
return false;
}
});
The prolem is how I can get value (especially primitive type) from the listenner. It always shows
Cannot refer to a non-final variable height inside an inner class defined in a different method
Then I try to change variable to final, it shows the error:
The final local variable height cannot be assigned, since it is defined in an enclosing type
I don’t know why the APIs are difficult to use.
The easiest way to deal with this is by letting your
ActivityimplementOnPreDrawListener.The issue is not with the ‘complexity’ of the API. This is a real Java problem regarding the life of the various variables involved. By not declaring the variable
heightfinal, it might be cleaned off the stack by the time your inner anonymous class tries to access it. By having to mark itfinal, you are being forced to guarantee the life ofheight.By doing what I suggested, you are equating the life of the Activity object and the listener Object.