android - 时间和日期显示

标签 android datetime-generation

如何在没有 java 或 Picker 的情况下显示日期和时间,就像 TimeView 一样简单

 android:@+id/ETC
 android:TextSize="" and so on. 

我将从设备获取时间或日期。时间/日期选择器占用了很多显示空间。

最佳答案

没有用于此的内置小部件,但您可以通过扩展 TextView 添加一个:

package com.example.widget;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimeView extends TextView {
  public TimeView(Context context) {
    super(context);
    updateTime();
  }

  public TimeView(Context context, AttributeSet attrs) {
    super(context, attrs);
    updateTime();
  }

  public TimeView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    updateTime();
  }

  public void updateTime() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String now = format.format(new Date());
    setText(now);
  }
}

然后您可以在您的 xml 文件中使用它,使用标准 TextView 参数对其进行自定义:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <com.example.widget.TimeView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#0f0"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

关于android - 时间和日期显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8451696/

相关文章:

c# - 需要根据年-周-日计算日期

mysql - 在日期范围之间进行选择并强制空行为 0?

android - 获取过去三年之间的数据,

android - 是否必须在应用程序包中包含所有可绘制文件夹的图标?

java - getExternalFilesDir() 是私有(private)的吗?

android - Android 中的谷歌地图聚类

android - Android 中的启动和停止按钮

java - setRetainInstance() 方法是否保留 ArrayAdapter 数据?