本篇文章為大家展示了怎么在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是一種基于Linux內核的自由及開放源代碼的操作系統,主要使用于移動設備,如智能手機和平板電腦,由美國Google公司和開放手機聯盟領導及開發。
上述內容就是怎么在Android中使用DatePickerDialog和TimePickerDialog實現時間日期對話框,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。