Android 从代码引用字符串资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10698945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:39:34  来源:igfitidea点击:

Reference string resource from code

androidstringsettext

提问by scarhand

I have the following string declared in strings.xml:

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

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

Now when someone clicks a button, I want a textview to show this string, with a space, then a variable value that is a timestamp.

现在当有人点击一个按钮时,我想要一个 textview 显示这个字符串,一个空格,然后是一个时间戳的变量值。

Unfortunately, using @string/last_msg isn't working, and I'm not sure how to do this properly so I'm not hardcoding in content.

不幸的是,使用 @string/last_msg 不起作用,我不确定如何正确执行此操作,因此我没有对内容进行硬编码。

Here's my code for the onClick function:

这是我的 onClick 函数代码:

public void showMsgNow(View view) {
    TextView lastMsg = (TextView)findViewById(R.id.textView2);
    long currentTimeStamp = System.currentTimeMillis();
    lastMsg.setText(@string/last_msg + " " + currentTimeStamp);
}

I'm a newbie, any help would be great !

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

回答by scarhand

I found the answer on Google:

我在谷歌上找到了答案:

getString(R.string.last_msg)

回答by Mohammed Azharuddin Shaikh

you cant access Stringdirectly by @, for that you need to have context resource and then just do this...

你不能String直接访问@,因为你需要有上下文资源,然后就这样做......

lastMsg.setText(context.getResources().getString(R.string.last_msg) + " " + currentTimeStamp);

in your case use

在你的情况下使用

<string name="last_msg">Your last click was on %1$s</string>

implementation:

执行:

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

回答by Sandeep P

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

回答by AAnkit

use below line

使用下面的行

 lastMsg.setText(getString(R.string.last_msg) + " " + currentTimeStamp);

回答by Kumar Vivek Mitra

Try this :

尝试这个 :

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