I have Constants java class in my android project and I want to create a layout.xml.

In the xml file I want to access the public static final fields from my Constants class.

How can I do that ?




public class Constants {
    public static final String HelloMessage = "Hello Dear Users";
Question author Oleg | Source



The correct way to manage string resources for Android is using the string.xml file in your res/values folder.

However you can also set the text of a UI widget programmatically if you need to. This would generally be used for dynamic text but there's nothing to stop you continuing to use static Strings in your Constants class.

In the Activity or Fragment which inflates the layout containing, for example, your RadioButton above, you need to get a reference to it, and then set the text. To get a reference you'll first need to give the RadioButton an id in XML:

<RadioButton    android:id="@+id/radio_button"    android:layout_width="wrap_content"    android:layout_height="wrap_content" />

And then programmatically set the text using the Constants string:

@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    RadioButton radioButton = (RadioButton) findViewById(R.id.radio_button);    radioButton.setText(Constants.HelloMessage);}

A note on style, your string variable should be in camel case, so should be helloMessage.

Answer author R3flss-exlutr

Ask about this question here!