MainActivity.java
import java.util.Calendar; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv_time, tv_day, tv_week; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_time = (TextView) findViewById(R.id.time); tv_day = (TextView) findViewById(R.id.day); tv_week = (TextView) findViewById(R.id.week); handler.post(runnable); } private Handler handler = new Handler(); private Runnable runnable = new Runnable() { public void run() { gettime(); handler.postDelayed(this, 1000); } }; public void gettime() { Calendar calendar = Calendar.getInstance(); // 获取年,月,日; String year = calendar.get(Calendar.YEAR) + ""; int month = calendar.get((Calendar.MONTH)) + 1; String day = calendar.get(Calendar.DAY_OF_MONTH) + ""; String yearString = year + "/" + (month) + "/" + day; tv_day.setText(yearString); // 获取系统时间 int hour = calendar.get(Calendar.HOUR_OF_DAY); String minute = calendar.get(Calendar.MINUTE) + ""; int miao = calendar.get(Calendar.SECOND); String timeString = hour + ":" + minute + ":" + miao; tv_time.setText(timeString); // 获取系统星期几 int week = calendar.get(Calendar.DAY_OF_WEEK); String weekString = null; switch (week) { case 1: weekString = "天"; break; case 2: weekString = "一"; break; case 3: weekString = "二"; break; case 4: weekString = "三"; break; case 5: weekString = "四"; break; case 6: weekString = "五"; break; case 7: weekString = "六"; break; } tv_week.setText("星期" + weekString); } }
布局文件:
<LinearLayout 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:orientation="horizontal" > <TextView android:id="@+id/time" android:layout_width="80dp" android:layout_height="60dp" android:gravity="center" android:text="时间" /> <TextView android:layout_width="1dp" android:layout_height="60dp" android:text="|" android:textColor="#060" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/day" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="日期" /> <TextView android:id="@+id/week" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="星期天" /> </LinearLayout> </LinearLayout>