Android 代码中使用字符串方法。

本文介绍在Android开发中如何更高效地使用字符串资源。通过Context类的getString方法可以直接获取字符串资源,支持格式化输出,简化了代码,提高了开发效率。

在Android中要使用字符串一般要用到Resources。使用它的getString方法即可

通常我们如下定义:

Resources mResources;

mResources = getResources();

然后调用mResources.getString(R.string.xxx);

格式化的时候使用String.format(mResources.getString(R.string.xxx),args); 在写这个文章前,我也是这么使用的。


但是今天看到了一个代码,真的是自惭形秽。如此常用的功能Android 怎么会没有自己写好的方法呢。代码是这么写的:

mTextView.setText(getString(R.string.text, 0));

跟进了下发现其实此方法就在Context类里,就在Context类里,就在Context类里,此时我是崩溃的。如此基础的类却不知道还存在这么个方法。

/**
 * Returns a localized string from the application's package's
 * default string table.
 *
 * @param resId Resource id for the string
 * @return The string data associated with the resource, stripped of styled
 *         text information.
 */
@NonNull
public final String getString(@StringRes int resId) {
    return getResources().getString(resId);
}

/**
 * Returns 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.
 * @return The string data associated with the resource, formatted and
 *         stripped of styled text information.
 */
@NonNull
public final String getString(@StringRes int resId, Object... formatArgs) {
    return getResources().getString(resId, formatArgs);
}
两个方法,一个是直接获取字符串,一个是带参数的字符串。


哎,还有好多好学西的,加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值