【问题标题】:Reference string resource from code从代码中引用字符串资源
【发布时间】:2012-05-28 18:17:07
【问题描述】:

我在 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/web 上搜索,这是您甚至可以在文档中找到的简单内容。

标签: android string settext


【解决方案1】:

我在谷歌上找到了答案:

getString(R.string.last_msg)

【讨论】:

  • 澄清一下,这里是android.content.Context#getString
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    // 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函数??
    • 当我不使用 getString 函数时,它只是作为整数而不是字符串出现...
    • 这里不用用,在android R中是Resource类,所有存放在raw文件夹中的资源在R类中都有id
    • String myString = lastMsg.getString().toString();
    • 这不起作用,因为 R.string.last_msg 是 int,您不能将 String 添加到 int。您至少必须使用 getString()。有关示例,请参见@Ankit 的答案。
    【解决方案4】:

    使用下面的行

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

    【讨论】:

      【解决方案5】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-08
        • 1970-01-01
        • 1970-01-01
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多