我在 strings.xml 中声明了以下字符串:

<string name="last_msg">Your last click was on</string>

现在,当有人单击按钮时,我想要一个文本视图来显示该字符串,其中包含一个空格,然后是一个时间戳变量值。

不幸的是,使用 @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);
}

我是新手,任何帮助都会很棒!

有帮助吗?

解决方案

我在谷歌上找到了答案:

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()));
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top