我有以下字符串中的strings.xml声明:
<string name="last_msg">Your last click was on</string>
现在,当有人点击一个按钮,我想一个TextView显示这个字符串,用空格,那么这是一个时间戳的变量值。
不幸的是,使用@字符串/ 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);
}
我是个新手,任何帮助将是巨大的!
我发现谷歌的答案:
getString(R.string.last_msg)
你不能访问String
直接@
,对于你需要有背景资源,然后只是这样做...
lastMsg.setText(context.getResources().getString(R.string.last_msg) + " " + currentTimeStamp);
在你的情况下使用
<string name="last_msg">Your last click was on %1$s</string>
执行:
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));
}
// 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);
}
使用以下线
lastMsg.setText(getString(R.string.last_msg) + " " + currentTimeStamp);
试试这个 :
lastMsg.setText(R.string.last_msg + " " + new SimpleDateFormat(d-MM-YYYY).format(new Date()));