2016-08-18 27 views
1

我有Constants我的android项目中的java类,我想创建一个layout.xml。访问android layout.xml中的静态类字段

在xml文件中,我想从我的Constants类访问public static final字段。

我该怎么做?

layout.xml

<RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text=Constants.HelloMessage/> 

Constants.java

public class Constants { 
    public static final String HelloMessage = "Hello Dear Users"; 
} 
+2

第一:你的values-folder中有一个'strings.xml'。这正是你想要的。第二:你不能从XML访问代码变量。您必须在活动初始​​化时手动设置它们,最好在'onCreate'-方法中。 – Bobby

+1

@ManuToMatic你是否建议我将所有常量从Constants.java类移动到strings.xml? – Oleg

+1

@Oleg ...或以编程方式将其分配给活动。 – FrozenFire

回答

3

为Android管理字符串资源的正确方法是在res/values文件夹中使用string.xml file

但是,如果需要,还可以以编程方式设置UI小部件的文本。这通常用于动态文本,但没有什么可阻止您继续在Constants类中使用静态String

ActivityFragment,其中包含,例如,您的RadioButton上面的布局膨胀,你需要得到它的引用,然后设置文本。为了让您首先需要给RadioButton的ID在XML参考:

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

,然后使用常量字符串编程设置文本:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    RadioButton radioButton = (RadioButton) findViewById(R.id.radio_button); 
    radioButton.setText(Constants.HelloMessage); 
} 

了一份关于风格,你的字符串变量应该在camel case,所以应该是helloMessage

2

更改XML以下

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

在您的Java类,

RadioButton radBtn=(RadioButton)findViewById(R.id.radBtnId); 
radBtn.setText(Constants.HelloMessage); 

否则你可以提到在strings.xml中的字符串如直接在XML文件中

<string name="tag">Name</string> 
1

使用strings.xml指用于这一目的。你的做法是错误的。

转到res文件夹,然后转到values> strings.xml。打开它,把你的字符串有喜欢

<resources> 
    <string name="hello_message">Hello Dear Users</string> 
<resources> 

然后在你的布局

<RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:[email protected]/hello_message/> 

希望这会有所帮助。

+0

如果我有ints或float常量,它们是否也应放在strings.xml中? 听起来strings.xml中只定义字符串有点不对 – Oleg

+0

。和'''的android:text'''只接受字符串不是int或漂浮 –

+0

但每一个数字可以表示为字符串@ZeeshanShabbir。例如,您可以定义一个值为“11”的字符串。 – Bobby