sca*_*and 5 string android settext
我在strings.xml中声明了以下字符串:
<string name="last_msg">Your last click was on</string>
Run Code Online (Sandbox Code Playgroud)
现在当有人点击按钮时,我希望textview显示带有空格的字符串,然后显示一个时间戳的变量值.
不幸的是,使用@ string/last_msg不起作用,我不知道如何正确地做到这一点所以我不是硬编码的内容.
这是我的onClick函数的代码:
public void showMsgNow(View view) {
TextView lastMsg = (TextView)findViewById(R.id.textView2);
long currentTimeStamp = System.currentTimeMillis();
lastMsg.setText(@string/last_msg + " " + currentTimeStamp);
}
Run Code Online (Sandbox Code Playgroud)
我是新手,任何帮助都会很棒!
Moh*_*ikh 10
你不能String直接访问@,因为你需要有上下文资源然后只是这样做...
lastMsg.setText(context.getResources().getString(R.string.last_msg) + " " + currentTimeStamp);
Run Code Online (Sandbox Code Playgroud)
在你的情况下使用
<string name="last_msg">Your last click was on %1$s</string>
Run Code Online (Sandbox Code Playgroud)
执行:
public void showMsgNow(View view) {
TextView lastMsg = (TextView)findViewById(R.id.textView2);
long currentTimeStamp = System.currentTimeMillis();
lastMsg.setText(context.getResources()
.getString(R.string.last_msg, currentTimeStamp));
}
Run Code Online (Sandbox Code Playgroud)
// getString is method of context
if (this instanceof Context)
//If you are in Activity or Service class
lastMsg.setText(getString(R.string.last_msg)+ " " + currentTimeStamp);
else
//you need to context to get the string
lastMsg.setText(getString(mContext,R.string.last_msg)+ " " + currentTimeStamp);
public String getString(Context mContext, int id){
return mContext.getResources().getString(id);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24912 次 |
| 最近记录: |