You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android小组件TextClock无法跟随系统切换24小时制怎么解决?

解决方案

问题根因

  • 桌面小组件依赖RemoteViews渲染,TextClock默认不会自动监听系统时间格式变更事件,因此系统切换12/24小时制后,小组件不会主动触发刷新。
  • 若手动配置format12Hour和format24Hour时硬编码写死格式,也会增加自动切换失效的概率。

具体修复步骤

第一步:调整布局中TextClock的属性配置

优先使用系统标准格式,修改后的布局代码如下:

<TextClock
    android:id="@+id/lw02_clock"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:fontFamily="sans-serif-thin"
    android:textSize="@dimen/_50ssp"
    android:textColor="@android:color/white"
    android:format12Hour="@android:string/time_format_12_hour"
    android:format24Hour="@android:string/time_format_24_hour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

如果不需要自定义格式,也可以直接删除两个format属性,TextClock会默认调用系统标准格式。

第二步:在小组件的AppWidgetProvider中注册监听系统相关变更广播

在你的小组件对应的AppWidgetProvider子类中,添加对时间、时区、配置变更广播的监听,收到广播后主动触发小组件刷新即可,示例代码如下:

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    String action = intent.getAction();
    // 监听时间格式、时间、时区变更事件
    if (Intent.ACTION_TIME_CHANGED.equals(action)
        || Intent.ACTION_TIMEZONE_CHANGED.equals(action)
        || Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
        // 调用原有刷新小组件的方法,触发RemoteViews重新渲染TextClock
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, 你的小组件Provider类名.class));
        onUpdate(context, appWidgetManager, appWidgetIds);
    }
}

同时要在AndroidManifest.xml中对应的小组件Receiver节点下添加对应的intent-filter:

<receiver android:name="你的小组件Provider类名">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        <!-- 新增以下三个监听配置 -->
        <action android:name="android.intent.action.TIME_SET" />
        <action android:name="android.intent.action.TIMEZONE_CHANGED" />
        <action android:name="android.intent.action.CONFIGURATION_CHANGED" />
    </intent-filter>
    <meta-data
        android:name="android.appwidget.provider"
        android:resource="@xml/你的小组件配置文件" />
</receiver>

第三步:验证效果

修改完成后重新安装应用,添加小组件到桌面,切换系统的12/24小时制开关,即可看到TextClock自动切换对应格式。

内容的提问来源于stack exchange,提问作者roly151

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:45:09