CodenameOne上的String.format替代 [英] String.format alternative on CodenameOne

查看:46
本文介绍了CodenameOne上的String.format替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将基于Java的库移植到CodenameOne以便在跨平台项目中使用它,但是它使用了很多Java标准API,而我在CodenameOne中找不到,首先是 String.format

I'm trying to port a Java-based library to CodenameOne in order to use it in a cross-platform project but it uses a lot of Java standard APIs that I cannot find in CodenameOne, first of all String.format.

我已阅读此问与答,我了解到有一些实用程序库可实现基类中缺少的内容。
是否有一个实现 String.format 的库类?

I have read this Q&A and I understood there are a few utility libraries which implement what's missing in base classes. Is there a library class which implements String.format?

例如,我需要做 String.format(%02d:%02d:%02d,hh,mm,ss);

推荐答案

您可以使用 com.codename1.l10n.SimpleDateFormat 来格式化时间,尽管我个人只是使​​用实用Java代码来格式化,因为它更简单。有了 Date ,我们便进入了时区的复杂性,这真是令人头疼。

You can use com.codename1.l10n.SimpleDateFormat to format time although personally I just use utility Java code to format as it's simpler. With Date we get into the timezone complexities and that's a pain in the neck.

我通常会这样做:

public static String twoDigits(int v) {
    return v < 10 ? "0" + v : "" + v;
}

然后:

String t = twoDigits(hh) + ":" + twoDigits(mm) + ":" + twoDigits(ss);

请注意,此代码比 Format 代码。 Format 调用需要解析格式,然后生成结果字符串,这是一个昂贵的步骤。在大多数情况下,可能不会引起注意。

Notice that this code is more efficient than the Format code. The Format call needs to parse the formatting then generate the resulting string which is a costly step. Probably won't be noticeable for most cases though.

String.format()的主要问题是 String中是否存在。由于String是实现的核心部分,因此类似的复杂方法将增加每个应用程序的权重,而无需考虑。同样,实现如此细微差别的方法也意味着事情在模拟器上和设备上的工作方式将有所不同。因此,我们极不可能添加该方法。

The main problem we have with String.format() is it's presence in String. Since String is a core part of the implementation a complex method like that will add weight to every application regardless of need. Also implementing a method like that with so many nuances would mean things would work differently on the simulator than on the device. So it's highly unlikely that we'll ever add that method.

实际上,在JavaSE上,该方法实际上只是 MessageFormat ,我们可以在codename1 l10n包中添加它。不兼容不是问题,大小/复杂性也不会。您可以自己实现此目的,如果需要,甚至可以作为请求请求提交。您可以将实现基于Apache许可的和谐项目源,也可以构建一个无尘室实现(我通常发现这更容易)。

In fact on JavaSE that method is really just a form of MessageFormat which is something we could add in the codename1 l10n package. Incompatibility wouldn't be a problem and neither would size/complexity. This is something you can implement yourself and even submit as a pull request if you so desire. You can base your implementation on the Apache licensed harmony project sources or you can build a clean room implementation (which I often found to be easier).

这篇关于CodenameOne上的String.format替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆