Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在按钮上显示日期(Android)_Android_Date_Button_Time - Fatal编程技术网

在按钮上显示日期(Android)

在按钮上显示日期(Android),android,date,button,time,Android,Date,Button,Time,我正在做一个编程练习,其中我有一个显示当前日期的按钮。在这个程序中,我需要为活动使用OnClickListener;使用Java Date类获取当前时间和日期,并使用按钮的setText()方法将该日期显示为按钮的标题 我在.xml文件中创建了以下按钮: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/

我正在做一个编程练习,其中我有一个显示当前日期的按钮。在这个程序中,我需要为活动使用OnClickListener;使用Java Date类获取当前时间和日期,并使用按钮的setText()方法将该日期显示为按钮的标题

我在.xml文件中创建了以下按钮:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="edu.arizona.uas.fonji.hellodate.HelloDate" >

    <Button
        android:id="@+id/date_button"
        android:layout_width="400dp"
        android:layout_height="3000dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

在代码中添加以下行:

        @Override
        public void onClick(View v) {
            date.setTime(System.currentTimeMillis()); //set to current time
            dateButton.setText(date.toString());
        }
如果要更改格式,则应使用
SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateButton.setText(dateFormat.format(date));

android:layout\u width=“400dp”android:layout\u height=“3000dp”您确定不应该只使用fill\u parent和fill\u parent?您希望日期以哪种格式显示?代码运行良好。你有什么问题?你能粘贴你的日志吗?Hello@Nava2011谢谢你的反馈。我对这一切都不熟悉。当我运行模拟器时,我没有意识到我必须首先单击按钮才能显示日期。我希望它在没有初次点击按钮的情况下出现。是的,你是对的,代码正在运行。谢谢你的邀请feedback@joao2fast4u日期的格式无关紧要。谢谢您好@zhuinden非常感谢您的帮助。它非常有用,而且确实帮助解决了这个问题。我没有添加代码,而是用您提供的代码替换了我编写的代码。再次感谢您用户3839913 16分钟前
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateButton.setText(dateFormat.format(date));