所以我按照文档here将XML字符串值与其他内容连接起来,结果得到以下代码:
//XML strings.xml
<string name="start_next_act_string">The next activity has been scheduled to automatically launch in %1$d seconds!</string>
//layout/activity_home.XML
<TextView
android:text="@string/start_next_act_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
//Home.java inside class, but outside oncreate
int startNextActivityInSeconds = 10;
//Home.java inside class and inside oncreate
super.onCreate(savedInstanceState);
Resources res = getResources();
String text = String.format(res.getString(R.string.start_next_act_string), startNextActivityInSeconds);
setContentView(R.layout.activity_home);
但是在Android屏幕上会打印出来
下一个活动已安排在%1 $ d秒内自动启动!
而不是
下一个活动已计划在10秒内自动启动!
如何更新XML字符串,以便显示连续的字符串结果?
答案 0 :(得分:1)
我担心你尝试做的事情不起作用。当布局膨胀时,字符串的使用方式与资源文件中的定义完全相同。
为此,您必须明确设置文本,即
setContentView(R.layout.activity_home);
TextView tv = (TextView)findViewById(R.id.theId);
tv.setText(text);
其中&#34; theId&#34;是您必须在xml文件中为TextView设置的ID,例如:
<TextView
android:id="@+id/theId"
android:text="@string/start_next_act_string"
...
答案 1 :(得分:0)
您需要将TextView
的text属性设置为您创建的新String,否则格式化的字符串将仅存储在您的本地String中,并且不会反映在UI中。
首先,您需要通过为其提供ID来命名TextView:
<TextView
android:id="@+id/YourId"
...
然后,从Activity
绑定到视图并主动修改其文本:
TextView myTextView = (TextView)findViewById(R.id.YourId);
myTextView.setText(text);