android中%1$s、%1$d的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mattdong0106/article/details/51077708

作用:

动态的拼接字符串,使代码更简洁,更易维护、易扩展。

用法:

1.整型:
比如:“他今年XX岁了”,这个具体XX岁可能需要从服务端取的,那我们可以这么写

<string name="old">他今年%1$d岁了</string>

在程序中

TextView tvOld = (TextView)findViewById(R.id.tv_old);
tvOld.setText(getContext().getString(R.string.old, 18));

执行结果就是:“他今年18岁了”。
“%1$d”表达的意思是整个name=”old”中,第一个整型的替代。如果一个name中有两个需要替换的整型内容,则第二个写为:%2$d,以此类推;具体程序中替换见下面的string型;

插个话,getString()方法的第二个参数是个可变参数,参见源码:

  /**
 * Return a localized formatted string from the application's package's
 * default string table, substituting the format arguments as defined in
 * {@link java.util.Formatter} and {@link java.lang.String#format}.
 *
 * @param resId Resource id for the format string
 * @param formatArgs The format arguments that will be used for substitution.
 */

public final String getString(int resId, Object... formatArgs) {
    return getResources().getString(resId, formatArgs);
}

2.String类型
比如,“我叫XX,来自XXX”,这里的XX和XXX都需要替换,在strings.xml中可以这么写:

<string name="introduce">我的名字叫%1$s,我来自%2$s</string>

在程序中:

 TextView tvIntroduce = (TextView)findViewById(R.id.tv_introduce);
 tvIntroduce.setText(getContext().getString(R.string.introduce, “宋仲基”,“太阳”));

执行结果就是:“我的名字叫宋仲基,我来自太阳”。

当然,如果一句话里边只有一个占位符的话,可以直接用%s或%d。

猜你喜欢

转载自blog.csdn.net/mattdong0106/article/details/51077708