androidandroid-layoutclass-constants

How to use a Constant value of a class field in a layout?


I would like to use some java class constant value in my XML layout. Is that possible?

java class

public class ConstantKey {

   public static final String COUNTRY_CODE            = "+00";
   public static final STRING COUNTRY_NAME            = "USA";

}

Xml layout

    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="ConstantKey.COUNTRY_NAME"/>

Solution

  • You could:

    1) If the strings are constant all through, you could add them as string resources inside strings.xml. This way they're accessed from both layout or java code.

    2) If the values depend on a network call or are dynamically computed, I suggest using DataBinding in andorid, check my answer here for small implementation example.