从代码中引用字符串资源

5
我在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);
}

我是个新手,任何帮助都将不胜感激!


在发布问题之前,请先在Google/网络上搜索,这是您甚至可以在文档中找到的简单事情。 - AAnkit
5个回答

11
我在谷歌上找到了答案:
getString(R.string.last_msg)

澄清一下,这是 android.content.Context#getString - Alexander Terp

10

你不能直接通过@访问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));
}

6
// 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);
  }

那么我不需要使用getString函数吗? - scarhand
当我不使用getString函数时,它只显示为整数而不是字符串... - scarhand
不需要在Android中使用此处,R是资源类,所有存储在raw文件夹中的资源都具有R类中的ID。 - Sandeep P
字符串 myString = lastMsg.getString().toString(); - Sandeep P
这不起作用,因为R.string.last_msg是一个int类型,你不能将String添加到int中。你至少需要使用getString()。请参考@Ankit的答案示例。 - Marc Plano-Lesay

1
请使用以下行:
 lastMsg.setText(getString(R.string.last_msg) + " " + currentTimeStamp);

0

试试这个:

lastMsg.setText(R.string.last_msg + " " + new SimpleDateFormat(d-MM-YYYY).format(new Date()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接