How to use final values ​​inside CustomView? Trying to do as follows:

public class CustomView extends View { private static final int x; public CustomView(Context context, AttributeSet attrs) { super(context, attrs); x = getX(); } } 

, but writes that the variable is not initialized. I don’t want to immediately indicate the value during the declaration, since it will be necessary to first get this value from the code.

  • Is it necessary to make final variable? If you assign it a value in the course of the program's work, then it loses the definition of a constant - Werder
  • @Werder if it is final, the studio will not allow it to change - iamtihonov

1 answer 1

The problem you have is static, not final. Either initialize it or declare it as non-static. Static variables are initialized when the class is loaded (not to be confused with the creation of a class object).

However, you can still initialize the variable "from the code", more precisely from the static method.

 private static final int x; static { x = getX(); } private static int getX(){ return 100500; } 

or simply

 private static final int x = getX(); 

or even easier

 private static final int x = 100500; 
  • It turns out to create a static variable dependent on the Context will not work, and I think it is not very good. - iamtihonov
  • and it turns out that it will not work to use final variables inside CustomView or Fragment, whose values ​​depend on the same Context, since they have not yet joined the Activity in the constructor. - iamtihonov