代碼:
package com.test; import java.util.Calendar; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; public class MainActivity extends Activity { private Button button; TextView textView; StringBuffer stringBuilder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button1); textView=(TextView)findViewById(R.id.textView1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Calendar c=Calendar.getInstance(); Dialog dateDialog=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub stringBuilder=new StringBuffer(""); stringBuilder.append(arg1+"-"+(arg2+1)+"-"+arg3+" "); Calendar time=Calendar.getInstance(); Dialog timeDialog=new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub stringBuilder.append(hourOfDay+":"+minute); textView.setText("您設置的時間為:"+stringBuilder); } }, time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), true); timeDialog.setTitle("請選擇時間"); timeDialog.show(); } }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); dateDialog.setTitle("請選擇日期"); dateDialog.show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
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=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:text="單擊彈出日歷對話框" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/button1" android:layout_alignLeft="@+id/button1" android:layout_marginBottom="84dp" android:layout_marginLeft="44dp" android:text="TextView" /> </RelativeLayout>
實現效果