Android TextClock获取系统时间,格式跟随设置改变

来源:互联网 发布:鹏业软件青海 编辑:程序博客网 时间:2024/05/04 12:05
<TextClock                android:id="@+id/textclock"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:format12Hour="yyyy/dd/MM"                android:format24Hour="yyyy/dd/MM"                android:textStyle="normal"                android:fontFamily="sans-serif-light"                android:textSize="30px" />

这是一个textClock,也就是数字时钟,可以看到在XML 布局中,通过定义format 12Hour或者24Hour可以实现不同的格式下输出的内容,yyyy/dd/MM(注意MM是大写的,不然就成了时间里的分,m),输入格式是2015/01/15,如果是yy/dd/MM,那么输出的是15/01/15 ,也可以把 / 换成 - 。

<TextClock                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_marginTop="5.3dp"                android:format24Hour="H:mm"                android:format12Hour="h:mm"                android:textStyle="normal"                android:fontFamily="sans-serif-light"                android:textSize="46sp"                 />
H:mm和h:mm的区别就是一个是12小时格式,一个是24小时格式。

                android:format24Hour=""                android:format12Hour="aa"
上边代码意思是,24小时格式中,不显示上下午的文字,12小时格式中,显示上下午。

我们在设置中可以选择日期样式,例如2015 - 15 -01、2015 - 01- 15等等,但是怎样根据我们设置的格式,显示想对应的格式呢?

在onCreate()方法中和void showWorkspace(boolean animated)方法中分别添加如下代码:

if (!("").equals(getDateFormate(this))){        textClock.setFormat12Hour(getDateFormate(this));     textClock.setFormat24Hour(getDateFormate(this));        } else {        textClock.setFormat12Hour("yyyy-dd-MM");     textClock.setFormat24Hour("yyyy-dd-MM");        } 
在主程序中添加如下代码:

private String getDateFormate(Context context){    return Settings.System.getString(context.getContentResolver(),     Settings.System.DATE_FORMAT);    }
上述代码的意思是从系统设置中获取选择的格式内容,首先判断是否为空(因为有个选项是根据地区自动判断,内容为“ ”),然后在对textClock进行设置对于的格式。

3 0
原创粉丝点击