Android DigitalClock自定义日期输出格式

前言

  关键字: DigitalClock date format

  Android的DigitalClock并没有设置输出格式的属性或方法,但是可以通过继承重写来实现,见正文部分代码。

正文

  一、需求

    修改时间输出格式为仅显示小时和分钟。

  二、效果图

三、说明

    通过看源码可知,只需修改以下两行代码其他全部复制过来即可:

private final static String m12 = "h:mm:ss aa";
private final static String m24 = "k:mm:ss";

如果想做得更好更通用的话可以把设置日期格式的方法暴露出来,或者为其增加一个xml属性。

  四、完整代码

package com.test;

import java.util.Calendar;

import android.content.Context;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.AttributeSet;

/**
 * 自定义DigitalClock输出格式
 * @author  农民伯伯
 *
 */
public class DigitalClock extends android.widget.DigitalClock {

    Calendar mCalendar;
    private final static String m12 = "h:mm aa";//h:mm:ss aa
    private final static String m24 = "k:mm";//k:mm:ss
    private FormatChangeObserver mFormatChangeObserver;

    private Runnable mTicker;
    private Handler mHandler;

    private boolean mTickerStopped = false;

    String mFormat;

    public DigitalClock(Context context) {
        super(context);
        initClock(context);
    }

    public DigitalClock(Context context, AttributeSet attrs) {
        super(context, attrs);
        initClock(context);
    }

    private void initClock(Context context) {
        Resources r = context.getResources();

        if (mCalendar == null) {
            mCalendar = Calendar.getInstance();
        }

        mFormatChangeObserver = new FormatChangeObserver();
        getContext().getContentResolver().registerContentObserver(
                Settings.System.CONTENT_URI, true, mFormatChangeObserver);

        setFormat();
    }

    @Override
    protected void onAttachedToWindow() {
        mTickerStopped = false;
        super.onAttachedToWindow();
        mHandler = new Handler();

        /**
         * requests a tick on the next hard-second boundary
         */
        mTicker = new Runnable() {
                public void run() {
                    if (mTickerStopped) return;
                    mCalendar.setTimeInMillis(System.currentTimeMillis());
                    setText(DateFormat.format(mFormat, mCalendar));
                    invalidate();
                    long now = SystemClock.uptimeMillis();
                    long next = now + (1000 - now % 1000);
                    mHandler.postAtTime(mTicker, next);
                }
            };
        mTicker.run();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mTickerStopped = true;
    }

    /**
     * Pulls 12/24 mode from system settings
     */
    private boolean get24HourMode() {
        return android.text.format.DateFormat.is24HourFormat(getContext());
    }

    private void setFormat() {
        if (get24HourMode()) {
            mFormat = m24;
        } else {
            mFormat = m12;
        }
    }

    private class FormatChangeObserver extends ContentObserver {
        public FormatChangeObserver() {
            super(new Handler());
        }存为草稿         @Override
        public void onChange(boolean selfChange) {
            setFormat();
        }
    }
}

五、使用方法

<com.test.DigitalClock android:layout_x="15dp" android:layout_y="30dp" 
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textColor="@android :color/white" android:textSize="55sp"
             android:shadowColor="@android :color/white" android:shadowRadius="2.0"
            >
</com.test.DigitalClock>


转载于:https://my.oschina.net/amigos/blog/59536

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java编程实现数字时钟的示例代码,包括多种格式输出时间信息: ```java import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class DigitalClock { public static void main(String[] args) { while (true) { LocalTime now = LocalTime.now(); System.out.println("Current Time: " + now); // Format 1: hh:mm:ss DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("HH:mm:ss"); String time1 = now.format(formatter1); System.out.println("Time Format 1: " + time1); // Format 2: h:mm:ss a DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("h:mm:ss a"); String time2 = now.format(formatter2); System.out.println("Time Format 2: " + time2); // Format 3: HH:mm DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("HH:mm"); String time3 = now.format(formatter3); System.out.println("Time Format 3: " + time3); // Format 4: h:mm a DateTimeFormatter formatter4 = DateTimeFormatter.ofPattern("h:mm a"); String time4 = now.format(formatter4); System.out.println("Time Format 4: " + time4); try { Thread.sleep(1000); // Wait for 1 second } catch (InterruptedException e) { e.printStackTrace(); } // Clear console System.out.print("\033[H\033[2J"); System.out.flush(); } } } ``` 代码解释: - `LocalTime.now()` 获取当前时间对象; - `DateTimeFormatter` 定义时间格式; - `now.format(formatter)` 将时间对象格式化为指定格式的字符串; - `Thread.sleep(1000)` 使程序等待 1 秒钟; - `System.out.print("\033[H\033[2J")` 和 `System.out.flush()` 清空控制台输出。 运行示例代码,会不断输出当前时间和多种格式的时间信息,类似于数字时钟效果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值