Android 不同屏幕尺寸的不同日期格式

Android 不同屏幕尺寸的不同日期格式,android,resources,date-format,simpledateformat,Android,Resources,Date Format,Simpledateformat,我的android应用程序可以在桌子和手机上运行(阅读-大屏幕和小屏幕)。在我的整个应用程序中,我根据需要使用不同的资源(布局、尺寸、样式、字符串),将它们适当地放置在values或values-sw600dp中 但我一直在努力解决的一个问题是日期格式。在一些地方,我使用了DateFormat.LONG(比如2015年11月15日)。这在大屏幕上运行良好,但在小手机屏幕上,整个文本不适合,并且会被截断。为了解决这个问题,我想在小屏幕上使用不同的格式,例如DateFormat.MEDIUM(这将使

我的android应用程序可以在桌子和手机上运行(阅读-大屏幕和小屏幕)。在我的整个应用程序中,我根据需要使用不同的资源(布局、尺寸、样式、字符串),将它们适当地放置在
values
values-sw600dp

但我一直在努力解决的一个问题是日期格式。在一些地方,我使用了
DateFormat.LONG
(比如2015年11月15日)。这在大屏幕上运行良好,但在小手机屏幕上,整个文本不适合,并且会被截断。为了解决这个问题,我想在小屏幕上使用不同的格式,例如
DateFormat.MEDIUM
(这将使我在2015年11月15日
2015
可以很好地适应小屏幕)

我可以动态确定屏幕大小并使用一种或另一种格式。这感觉相当低效,我更愿意在参考资料中指定格式,以便以后可以轻松地更改它-但我找不到一种方法来做到这一点。我可以想到一些黑客——但它们确实是黑客(例如,在字符串资源中存储字符串
LONG
,然后在运行时使用反射在
DateFormat
中查找名为
LONG
的字段并获取其值)


那么,有没有一种简单的方法可以在参考资料中存储内置日期格式的指示符呢?

使用如下方法:

final int style = getResources().getInteger(R.integer.foobar__format_style);
DateFormat.getDateInstance(Utils.getDataFormatStyle(style));
第一次接近: DateFormat.format(getResources().getString(R.string.main_data_format),data.getTime()).toString()

在资源中,您将包含不同屏幕的格式

第二种方法: getDateInstance(getResources().getInteger(R.integer.data_格式_样式))

其中integer是以下各项之一:

public static final int DEFAULT = 2;
public static final int FULL = 0;
public static final int LONG = 1;
public static final int MEDIUM = 2;
public static final int SHORT = 3;
取决于屏幕大小的格式

为避免API将来更改时出现问题,您可以使用默认值准备自己的常量集:

   <resource>
   <integer name="data_format_default">202</integer>
   <integer name="data_format_full">200</integer>
   <integer name="data_format_long">201</integer>
   <integer name="data_format_medium">202</integer>
   <integer name="data_format_short">203</integer>
    </resource>
然后像这样使用它们:

final int style = getResources().getInteger(R.integer.foobar__format_style);
DateFormat.getDateInstance(Utils.getDataFormatStyle(style));

我最终使用了反射,因为它给了我最大的灵活性来轻松地改变事情。我现在得到的是:

在strings.xml中:


这不会达到与DateFormat.com相同的效果,只要它不适合不同的地区。我希望有不同的格式,但取决于语言环境。您仍然可以这样做,只需为所有屏幕和所有受支持的国家/地区定义资源。或者看看更新答案。为所有受支持的国家添加格式是不可行的——它们有数百种,我不知道它们是什么。至于你的更新,是的,我是这样想的,但是如果在下一个版本的android中谷歌改变了这些值,应用程序将无法正常工作。我们之所以按名称而不是按值使用这些常量,是有原因的。如果您真的害怕API在这种情况下的更改,请参阅我的更新答案。但我认为设施阅读有一个名字。
final int style = getResources().getInteger(R.integer.foobar__format_style);
DateFormat.getDateInstance(Utils.getDataFormatStyle(style));
<string name="title_date_format">LONG</string>
String formatString = getString(R.string.title_date_format);
int style = DatFormat.class.getField(formatString).getInt(null);
DateFormat format = DateFormat.getDateInstance(style);