![](/img/trans.png)
[英]Is it possible that a seekbar and listview be in a layout.xml in android?
[英]access static class fields in android layout.xml
我的android項目中有Constants
java類,我想創建一個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";
}
管理Android字符串資源的正確方法是使用res / values文件夾中的string.xml文件 。
但是,如果需要,還可以以編程方式設置UI窗口小部件的文本。 這通常用於動態文本,但沒有什么可以阻止你繼續在Constants類中使用靜態String
。
在包含例如上面的RadioButton
的布局的Activity
或Fragment
中,您需要獲取對它的引用,然后設置文本。 要獲得引用,首先需要為RadioButton
提供XML中的id:
<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);
}
關於樣式的注釋,你的字符串變量應該是駝峰式的 ,所以應該是helloMessage
。
將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中提到String,就像在xml文件中直接引用一樣
<string name="tag">Name</string>
為此,請使用strings.xml
。 你做的方式是錯的。
轉到res文件夾,然后轉到值> strings.xml。 打開它,把你的字符串放在那里
<resources>
<string name="hello_message">Hello Dear Users</string>
<resources>
然后在你的布局
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=@string/hello_message/>
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.