在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); }两个方法,一个是直接获取字符串,一个是带参数的字符串。
哎,还有好多好学西的,加油!
本文介绍在Android开发中如何更高效地使用字符串资源。通过Context类的getString方法可以直接获取字符串资源,支持格式化输出,简化了代码,提高了开发效率。
3019

被折叠的 条评论
为什么被折叠?



