本文實例講述了Android開發之DatePickerDialog、TimePickerDialog時間日期對話框用法。分享給大家供大家參考,具體如下:
用法:
一、創建兩個 DatePickerDialog、TimePickerDialog 實例調用 show() 方法即可將他們顯示出來
二、為 DatePickerDialog、TimePickerDialog 實例分別綁定監聽器,通過監聽獲得用戶設置
效果:
DatePickerDialog
TimePickerDialog
下面是具體的實現方法:
public class MainActivity extends Activity { private Button buttonDate; private Button buttonTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonDate = (Button) findViewById(R.id.dataBn); buttonTime = (Button) findViewById(R.id.timeBn); iniClick();//Binding the listeners for you program } public void iniClick(){ //set listener for your Date button buttonDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); //create a datePickerDialog and then shoe it on your screen new DatePickerDialog(MainActivity.this,//binding the listener for your DatePickerDialog new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { Toast.makeText(MainActivity.this,"Year:" + year + " Month:" + month + " Day:" + dayOfMonth,Toast.LENGTH_SHORT).show(); } } , calendar.get(Calendar.YEAR) , calendar.get(Calendar.MONTH) , calendar.get(Calendar.DAY_OF_MONTH)).show(); } }); //set listener for your Time button buttonTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); //create a datePickerDialog and then shoe it on your screen new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Toast.makeText(MainActivity.this,"Hour:" + hourOfDay + " Minute:" + minute ,Toast.LENGTH_SHORT).show(); } } , calendar.get(Calendar.HOUR_OF_DAY) , calendar.get(Calendar.MINUTE) , true).show(); } }); }}
這里是布局文件:
<?xml version="1.0" encoding="utf-8" ?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/idtatabHost" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:layout_weight="1"> <Button android:id="@+id/dataBn" android:text="點我一下 挑日期" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <Button android:id="@+id/timeBn" android:text="點我一下 挑時間 。。。" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /></LinearLayout>
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答