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

<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进行设置对于的格式。

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值