【问题标题】:How to put variable inside string-resources?如何将变量放入字符串资源中?
【发布时间】:2011-05-02 07:42:36
【问题描述】:

是否可以将变量放入字符串资源中?如果是的话 - 我该如何使用它们。

我需要的是:

<string name="next_x_results">Next %X results</string>

并用一个 int 代替 %X。

【问题讨论】:

    标签: java android


    【解决方案1】:
    <string name="meatShootingMessage">You shot %1$d pounds of meat!</string>  
    
    
    int numPoundsMeat = 123;
    String strMeatFormat = getResources().getString(R.string.meatShootingMessage, numPoundsMeat);
    

    示例取自here

    【讨论】:

    【解决方案2】:

    只需将它作为 formatArgs 对象传递给 getString() 函数即可。

    int nextResultsSize = getNextResultsSize();
    String strNextResultsSize = 
         getResources().getString(R.string.next_x_results, nextResultsSize);
    

    XML:

    <string name="next_x_results">Next %1$d results</string>
    

    【讨论】:

      【解决方案3】:
      <string name="message">You shot %1$d pounds of meat! Put Second Variable String here %2$s and third variable integer here %3$d</string>
      int intVariable1 = 123;
      String stringVariable2 = "your String";
      int intVariable3 = 456;
      String strMeatFormat = getResources().getString(R.string.message, intVariable1, stringVariable2 , intVaribale3);
      

      【讨论】:

      • 你是如何给stringVariable2中的int赋值的?
      • @salman 通过使用 %2$s ,我已将字符串值分配给第二位的字符串,而不是 int
      【解决方案4】:

      是的,你可以使用。 在将标签添加到 string.xml 文件然后在 .java 文件中检索相同的标签后,您可以按照此操作。

      安卓应用

      String str = getResources().getString(R.string.name);

      【讨论】:

        猜你喜欢
        • 2014-09-11
        • 2019-08-14
        • 1970-01-01
        • 2011-12-09
        • 2022-07-25
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多