您的位置:首页 > 移动开发 > Android开发

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

2016-04-12 16:30 423 查看
在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);
}

两个方法,一个是直接获取字符串,一个是带参数的字符串。

哎,还有好多好学西的,加油!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: