制作网站怎么做滚动条百度竞价推广价格
每个国家/地区代码使用一个文件的另一种方法(如安德鲁·怀特(Andrew White)和PJ_Finnegan的回答中所述)是仅定义一次HTML(例如,在TextUtil文件夹中),并在其中使用TextView ID,例如
@string/message_text
将资产加载到字符串中后,您可以将其内容传递给TextUtil:
/**
* Regex that matches a resource string such as @string/a-b_c1
.
*/
private static final String REGEX_RESOURCE_STRING = "@string/([A-Za-z0-9-_]*)";
/** Name of the resource type "string" as in @string/...
*/
private static final String DEF_TYPE_STRING = "string";
/**
* Recursively replaces resources such as @string/abc
with
* their localized values from the app's resource strings (e.g.
* strings.xml
) within a source
string.
*
* Also works recursively, that is, when a resource contains another
* resource that contains another resource, etc.
*
* @param source
* @return source
with replaced resources (if they exist)
*/
public static String replaceResourceStrings(Context context, String source) {
// Recursively resolve strings
Pattern p = Pattern.compile(REGEX_RESOURCE_STRING);
Matcher m = p.matcher(source);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String stringFromResources = getStringByName(context, m.group(1));
if (stringFromResources == null) {
Log.w(Constants.LOG,
"No String resource found for ID \"" + m.group(1)
+ "\" while inserting resources");
/*
* No need to try to load from defaults, android is trying that
* for us. If we're here, the resource does not exist. Just
* return its ID.
*/
stringFromResources = m.group(1);
}
m.appendReplacement(sb, // Recurse
replaceResourceStrings(context, stringFromResources));
}
m.appendTail(sb);
return sb.toString();
}
/**
* Returns the string value of a string resource (e.g. defined in
* values.xml
).
*
* @param name
* @return the value of the string resource or null
if no
* resource found for id
*/
public static String getStringByName(Context context, String name) {
int resourceId = getResourceId(context, DEF_TYPE_STRING, name);
if (resourceId != 0) {
return context.getString(resourceId);
} else {
return null;
}
}
/**
* Finds the numeric id of a string resource (e.g. defined in
* values.xml
).
*
* @param defType
* Optional default resource type to find, if "type/" is not
* included in the name. Can be null to require an explicit type.
*
* @param name
* the name of the desired resource
* @return the associated resource identifier. Returns 0 if no such resource
* was found. (0 is not a valid resource ID.)
*/
private static int getResourceId(Context context, String defType,
String name) {
return context.getResources().getIdentifier(name, defType,
context.getPackageName());
}
这种方法的好处是,您只需指定一次HTML的结构,然后使用android的本地化机制。 另外,它允许递归引用strings.xml中的字符串,TextUtil不支持。例如:
Some string @string/another_one.
缺点是解析是在运行时完成的,因此在应用程序中使用每种语言时,为每种语言指定专用的HTML会有更好的性能。
有关使用此代码将HTML从资产文件转换为可在TextView中显示的“可样式化” TextUtil(使用Kuitsi的TagHandler)的示例,请参见TextUtil。